Java как написать или

Java Operator – &, && (AND) || (OR) Logical Operators

We use operators in most programming languages to perform operations on variables.

They are divided into various categories like arithmetic operators, assignment operators, comparison operators, logical operators, and so on.

In this article, we will be talking about the bitwise AND operator, and the AND (&&) and OR (||) logical operators.

How to use the bitwiseAND operator

The symbol & denotes the bitwise AND operator. It evaluates the binary value of given numbers. The binary result of these numbers will be returned to us in base 10.

When the & operator starts its operation, it will evaluate the value of characters in both numbers starting from the left.

Let’s look at an example to help you understand better:

System.out.println(10 & 12);
// returns 8

Let’s break it down.

The binary value of 10 is 1010

The binary value of 12 is 1100

Here is something you should have in mind before we start the operation:

  • 1 and 0 => 0
  • 0 and 1 => 0
  • 1 and 1 => 1
  • 0 and 0 => 0

So let’s carry out the operation.

The first character for 10 is 1 and the first character for 12 is also 1 so:

1 and 1 = 1.

We move on to the second characters – 0 for 10 and 1 for 12:

1 and 0 = 0.

For the third characters – 1 for 10 and 0 for 12:

1 and 0 = 0.

For the fourth characters – 0 for 10 and 0 for 12:

0 and 0 = 0.

Now let’s combine all the returned characters. We would have 1000.

The binary value 1000 in base 10 is 8 and that is why our operation returned 8.

How to use the logical AND operator

Note that we use logical operators to evaluate conditions. They return either true or false based on the conditions given.

The symbol && denotes the AND operator. It evaluates two statements/conditions and returns true only when both statements/conditions are true.

Here is what the syntax looks like:

statment1/condition1 && statemnt2/condition2

As you can see above, there are two statements/conditions separated by the operator. The operator evaluates the value of both statements/conditions and gives us a result – true or false.

Here is an example:

System.out.println((10 > 2) && (8 > 4));
//true

The operation will return true because both conditions are true – 10 is greater than 2 and 8 is greater than 4. If either one of the conditions had an untrue logic then we would get false.

To better understand the && operator, you should know that both conditions must be true to get a value of true.

Here is another example that returns false:

System.out.println((2 > 10) && (8 > 4));
// false

Here, 2 is not greater than 10 but 8 is greater than 4 – so we get a false returned to us. This is because one of the conditions is not true.

  • If both conditions are true => true
  • If one of the two conditions is false => false
  • If both conditions are false => false

How to use the logical OR operator

We use the symbol || to denote the OR operator. This operator will only return false when both conditions are false. This means that if both conditions are true, we would get true returned, and if one of both conditions is true, we would also get a value of true returned to us.

Here is the syntax:

statment1/condition1 || statemnt2/condition2

Let’s go over a few examples.

System.out.println((6 < 1) || (4 > 2));  
// true

This returns true because one of conditions is true.

  • If both conditions are true => true
  • If one of the conditions is true => true
  • If both conditions are false => false

Conclusion

In this article, we learned how to use the bitwise & operator in Java and how the operation is carried out to give us a result.

We also learned how to use the && and || logical operators in Java. We learned what value each operation returns based on the conditions involved in the operation.

Happy Coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

#База знаний

  • 9 мар 2021

  • 12

Знакомимся с каждым, узнаём про короткую и полную схемы вычислений. Проводим побитовые операции с целыми числами. Всё закрепляем на примерах.

Артём Авдеев

Java-разработчик, преподаёт в Skillbox, осваивает машинное обучение.

Логические операции в Java возвращают значение типа boolean: true или false («правда» или «ложь»). Подробнее о булевом типе мы говорили здесь.

В языке Java есть шесть логических операторов. Первые четыре представлены в таблице ниже.

Логический оператор Обозначение в Java Выражение Результат
«И» (AND): конъюнкция, логическое умножение && true && true

false && false

true && false

false && true

true

false

false

false

Включающее «ИЛИ» (OR): дизъюнкция, логическое сложение || true || true

false || false

true || false

false || true

true

false

true

true

Исключающее «ИЛИ» (XOR): строгая дизъюнкция, логическое вычитание ^ true ^ true

false ^ false

true ^ false

false ^ true

false

false

true

true

«НЕ» (NOT): инверсия, отрицание ! !true

!false

false

true

Если коротко, то в условных выражениях, которые могут включать в себя и операторы сравнения (<, >, <=, >=, ==, !=). При вычислении они возвращают значение булева типа.

Условные выражения, в свою очередь, применяются в операторах ветвления (if-else, switch, тернарном). Подробнее об этих операторах тут.

Допустим, мы хотим проверить, что значение переменной a больше значений в переменных b и c. То есть сравнить операнд a с двумя другими. Нам поможет логический оператор && (И).

Логический оператор && (И) возвращает true, если слева и справа от него стоят значения true, а иначе — false.

Иными словами, если оба логических высказывания истинны, то и операция && (И) возвращает истину.

Первый пример

int a = 6;
int b = 3;
int c = 4;
boolean d = (a > b) && (a > c);
System.out.println(d);

--OUTPUT> true

Как вычисляется значение выражения (a > b) && (a > c):

Сначала проверяется условие (a > b). Оно вернёт true, так как 6 больше 4. Далее проверяется условие (a > c), которое также вернёт true, ведь 6 больше 3.

Теперь у нас с двух сторон от логического оператора && стоят значения true.

По определению выше или по таблице ещё выше, результат вычисления логического выражения (true && true) равен true.

Второй пример

int a = 6;
int b = 4;
int c = 7;
boolean d = (a > b) && (a > c);
System.out.println(d);

--OUTPUT> false

Результат операции (a > b) вернёт true, так как 6 больше 4, а операция (a > c) уже вернёт false, так как 6 не больше 7.

Значит, слева от логического оператора && стоит true, а справа — false. Следовательно, результат вычисления логического выражения (мы присвоили его булевой переменной d) будет false.

Третий пример

int a = 4;
int b = 5;
int c = 6;
boolean d = (a > b) && (a > c);
System.out.println(d);

--OUTPUT> false

Результат операции сравнения (a > b) равен false, а что вернёт операция (a > c), уже значения не имеет (смотрите определение выше) — результат вычисления логического выражения (мы присвоили его булевой переменной d) будет равен false.

Рассмотрим примеры с другими операторами.

int a = 4;
int b = 6;
int c = 3;
boolean d = (a > b) || (a > c);
System.out.println(d);

--OUTPUT> true

Порядок вычисления:

  1. (a > b) || (a > c)
  2. (4 > 6) || (4 > 3)
  3. false || (4 > 3)
  4. false || true
  5. true

Значение переменной d равно true.

int a = 9;
int b = 9;
boolean c = a > b || a != b;
System.out.println(c);

--OUTPUT> false

Теперь вычисляйте вы.

int a = 5;
int b = 6;
int c = 7;
boolean d = (b > a) ^ (c > a);
System.out.println(d);

--OUTPUT> false

Порядок вычисления:

  1. (b > a) ^ (c > a)
  2. (6 > 5) ^ (7 > 5)
  3. true ^ (7 > 5)
  4. true ^ true
  5. false

Значение d равно false.

О практическом применении XOR читайте здесь.

int a = 5;
int b = 9;
boolean d = !(a > b);
System.out.println(d);

--OUTPUT> true

Порядок вычисления:

  1. !(a > b)
  2. !(5 > 9)
  3. !false
  4. true

Значение d стало true.

&& и || называются сокращёнными логическими операторами AND и OR соответственно, или операторами короткой схемы вычислений. В спецификации Java их ещё зовут условными. Значения их операндов могут быть только булева типа.

В отличие от двойных, одиночные & и | называются операторами полной схемы вычислений. Значения их операндов могут быть как только булевыми, так и только целочисленными (вместе с оператором ^ они используются в побитовых операциях).

В том, что для операторов & и | всегда вычисляются значения обоих операндов, а при работе операторов && и || второй операнд вычисляется только по необходимости.

То есть иногда результат выражения однозначно определён уже по первому операнду:

  1. Если первый операнд && равен false, то второй не вычисляется, так как уже понятно, что результат всего выражения будет false.
  2. Если первый операнд || равен true, то второй не вычисляется, так как уже понятно, что || вернёт true.

&& и || используют как операторы булевой логики. Они оперируют значениями только булева типа и применяются только в логических выражениях.

&& и || позволяют экономить вычисления (применять короткую схему) и помогают избегать ошибок. Как это делается?

Начнём с оператора &&. Приведём фрагмент из таблицы выше:

Логический оператор Обозначение в Java Выражение Результат
«И» (AND): конъюнкция, логическое умножение && true && true

false && false

true && false

false && true

true

false

false

false

Рассмотрим выражение: (3 > 4) AND (5 > 4)

Мы видим, что операнд слева от оператора AND равен false. Смотрим на таблицу выше — и понимаем, что вычислять второй операнд бессмысленно, так как оператор AND уже точно вернёт false.

Именно по такой логике и работает оператор короткой схемы вычислений &&. Если выражение слева от него равно false, то выражение справа вычисляться не будет.

Так же и с оператором ||: если выражение слева от него равно true, то выражение справа не вычисляется, так как результат операции || всё равно будет true.

В большинстве случае применяют именно && и ||. При верном использовании они избавляют Java от ненужных вычислений и страхуют от некоторых ошибок.

Первый пример

int a = 3;
int b = 0;

boolean d = (b != 0) && (a/b > 0);
System.out.println(d);

--OUTPUT> false

Если вместо оператора && мы используем &, то получим ошибку (исключение) java.lang.ArithmeticException: / by zero:

int a = 3;
int b = 0;

boolean d = (b != 0) & (a/b > 0);
System.out.println(d);

--OUTPUT> Exception in thread <...> java.lang.ArithmeticException: / by zero
	at <...>

Ошибка возникнет тогда, когда Java попытается вычислить второй аргумент логического выражения, если первый равнялся false.

Иными словами, мы узнали, что b равно 0 (выражение b != 0 вернуло false) — и идём делить на b (делить на ноль), вычисляя значение второго операнда (a/b > 0).

Второй пример

public void printStringLengthMoreThenZero(String str) {
   if (str != null && str.length() > 0) {
       System.out.println(str.length());
   } else {
       System.out.println("Тут нечего считать!");
   }
}

Код выше выводит в консоль длину строки str, в которой есть хотя бы один символ. А если строка пуста или её значение равно null (то есть строковая переменная ни на что не указывает), в консоль выводится сообщение: «Тут нечего считать!»

Мы выбрали оператор короткой схемы вычислений && — и это правильно!

А вот если бы вместо этого использовали оператор полной схемы &, то наш код работал бы не так, как надо.

Мы получали бы ошибку NullPointerException каждый раз, когда вызываем метод для строковой переменной со значением null.

Посмотрим, что происходило бы при вычислении условия блока if:

  1. str != null & str.length() > 0
  2. null != null & str.length() > 0
  3. false & str.length() > 0 // тут возникает ошибка

Сперва вычисляется первый аргумент логического выражения, а именно str != null (иными словами, получаем ответ на вопрос «Строковая переменная не равна null?»). Получили false, значит всё же равна.

Дальше Java должна вычислить второй аргумент логического выражения, а именно str.length() > 0 (иными словами — проверяется «Число символов строки > 0?»).

Для этого вызывается метод str.length(), который должен вернуть целое значение. Оно и будет сравниваться с 0. Но у нас-то str равна null (возвращать методу нечего, строки нет). Тут Java и пожалуется на NullPointerException.

Когда в выражении несколько логических операторов, результат вычисляется с учётом их приоритета. Если нет логических скобок, то операции выполняются в таком порядке:

  1. ! (NOT)
  2. & (AND)
  3. ^ (XOR)
  4. | (OR)
  5. && (условный AND)
  6. || (условный OR)

Если одинаковые операции стоят по соседству, то раньше выполняется та, что левее.

Первый пример

boolean a = true ^ true & false;
System.out.println(a);

Вычислим true ^ true & false:

  1. Выбираем самый приоритетный оператор (если таких больше одного — тот, что левее). У нас самый приоритетный & (он здесь такой один).
  2. Смотрим, что слева и справа от него: это true и false соответственно.
  3. Вычисляем выражение true & false — получаем false.
  4. В исходном выражении заменяем true & false результатом его вычисления (false) — и получаем: true ^ false.
  5. Вычислив это выражение, получаем результат true.

Или короче:

  1. true ^ true & false
  2. true ^ false
  3. true

Второй пример

Заменим & на &&:

boolean a = true ^ true && false;
System.out.println(a);

Теперь самый приоритетный оператор в выражении это ^ — и порядок вычислений будет уже другой:

  1. true ^ true && false
  2. false && false
  3. false

Результат будет false.

Порядок вычисления логических операторов меняют круглые скобки — так же, как в арифметике:

boolean a = (true ^ true) & false;
System.out.println(a);

--OUTPUT> false

Добавив круглые скобки, мы поменяли приоритеты для вычисления. Теперь сперва будет определено выражение (true ^ true), которое вернёт false. А после — вычислится выражение false & false, которое тоже вернёт false.

То есть скобки повышают приоритет стоящего внутри выражения, а внутри самих скобок действуют прежние приоритеты.

Пример посложнее — выражение !(true && (false || true)) ^ !false.

Порядок вычисления:

  1. !(true && (false || true)) ^ !false
  2. !(true && true) ^ !false
  3. !true ^ !false
  4. false ^ !false
  5. false ^ true
  6. true

Результат: true.

Мы уже знаем, что логические операции применимы к логическим аргументам (операндам). Каждый логический операнд — это выражение, которое является истинным (true) или ложным (false) — то есть возвращает булево значение. Иными словами, логический операнд — это выражение типа boolean.

Выходит, применять логические операторы к целочисленным аргументам нельзя?

Можно. Внутри Java все целочисленные типы представлены двоичными числами разной длины. И к ним уже применимы бинарные логические операторы ^, | и &.

Только в этом случае они работают с двоичным представлением операндов — выполняют операции над их битами попарно (рассматривая их как логические единицы и нули). Поэтому и сами операторы ^, | и & зовутся побитовыми.

Рассмотрим пример:

int a = 3 & 5;
int b = 3 | 5;
int c = 3 ^ 5;
System.out.println(a);
System.out.println(b);
System.out.println(c);

--OUTPUT> 1
--OUTPUT> 7
--OUTPUT> 6

Чтобы повторить вычисления Java, нужно:

  1. Перевести значения обоих операндов в двоичную систему счисления.
  2. Расположить результаты перевода друг под другом.
  3. Сравнять в них число разрядов (дополнить лидирующими нулями).
  4. Применить к битам из каждого столбца оператор (&, | или ^).
  5. Записать результат каждой операции ниже в том же столбце.
  6. Перевести итог в десятичную форму.

Число 3 в двоичной системе счисления имеет вид 11, а число 5 — 101.

Так как у числа 5 три разряда в двоичной системе, а у числа 3 — всего два, добавим лидирующий ноль к числу 3 в двоичной системе и получим 011.

Берём цифры из обоих чисел и применяем к ним попарно оператор & (AND):

3(10) = 011(2) 0 1 1
& & &
5(10) = 101(2) 1 0 1
= = =
001(2) = 1(10) 0 0 1

Получаем число 001. В десятичной записи ему соответствует число 1. Поэтому операция 3 & 5 и возвращает в результате 1.

С оператором | действуем так же:

3(10)  = 011(2) 0 1 1
| | |
5(10) = 101(2) 1 0 1
= = =
111(2) = 7(10) 1 1 1
3(10)  = 011(2) 0 1 1
^ ^ ^
5(10) = 101(2) 1 0 1
= = =
110(2) = 6(10) 1 1 0

Сперва подытожим:

  • мы познакомились с логическими операторами в Java;
  • научились вычислять условные выражения с ними;
  • разобрались, как они работают с целыми числами.

В одной из статей мы говорили про операторы сравнения <, >, <=, >=, ==, !=, а также instanceof, про условные конструкции if-else и switch. Учились работать с тернарным оператором.

Если пропустили — лучше вернитесь и прочтите.

Учись бесплатно:
вебинары по программированию, маркетингу и дизайну.

Участвовать

Научитесь: Профессия Java-developer PRO
Узнать больше

Логические операторы

Логические операторы работают только с операндами типа boolean. Все логические операторы с двумя операндами объединяют два логических значения, образуя результирующее логическое значения. Не путайте с побитовыми логическими операторами.

Таблица логических операторов в Java

Оператор Описание
& Логическое AND (И)
&& Сокращённое AND
| Логическое OR (ИЛИ)
|| Сокращённое OR
^ Логическое XOR (исключающее OR (ИЛИ))
! Логическое унарное NOT (НЕ)
&= AND с присваиванием
|= OR с присваиванием
^= XOR с присваиванием
== Равно
!= Не равно
?: Тернарный (троичный) условный оператор

Логические операторы &, |, ^ действуют применительно к значениям типа boolean точно так же, как и по отношению к битам целочисленных значений. Логический оператор ! инвертирует (меняет на противоположный) булево состояние: !true == false и !false == true.

Таблица. Результаты выполнения логических операторов

A B A | B A & B A ^ B !A
false false false false false true
true false true false true false
false true true false true true
true true true true false false

Сокращённые логические операторы

Кроме стандартных операторов AND (&) и OR (|) существуют сокращённые операторы && и ||.

Если взглянуть на таблицу, то видно, что результат выполнения оператора OR равен true, когда значение операнда A равно true, независимо от значения операнда B. Аналогично, результат выполнения оператора AND равен false, когда значение операнда A равно false, независимо от значения операнда B. Получается, что нам не нужно вычислять значение второго операнда, если результат можно определить уже по первому операнду. Это становится удобным в тех случаях, когда значение правого операнда зависит от значения левого.

Рассмотрим следующий пример. Допустим, мы ввели правило — кормить или не кормить кота в зависимости от числа пойманных мышек в неделю. Причём число мышек зависит от веса кота. Чем больше кот, тем больше он должен поймать мышей.

Кот, прочитавший условие задачи, обиделся на меня. Он заявил, что я отстал от жизни, а на дворе 21 век — мышей можно ловить с помощью мышеловок. Пришлось объяснять ему, что это всего лишь задачка, а не пример из личной жизни.


int mouse; // число мышек
int weight; // вес кота в граммах
mouse = 5;
weight = 4500;

if (mouse != 0 & weight / mouse < 1000) {
	mInfoTextView.setText("Можно кормить кота");
}

Если запустить программу, то пример будет работать без проблем — пять мышей в неделю вполне достаточно, чтобы побаловать кота вкусным завтраком. Если он поймает четырёх мышей, то начнутся проблемы с питанием кота, но не с программой — она будет работать, просто не будет выводить сообщение о разрешении покормить дармоеда.

Теперь возьмём крайний случай. Кот обленился и не поймал ни одной мышки. Значение переменной mouse будет равно 0, а в выражении есть оператор деления. А делить на 0 нельзя и наша программа закроется с ошибкой. Казалось бы, мы предусмотрели вариант с 0, но Java вычисляет оба выражения mouse != 0 и weight / mouse < 1000, несмотря на то, что уже в первом выражении возвращается false.

Перепишем условие следующим образом (добавим всего лишь один символ):


if (mouse != 0 && weight / mouse < 1000) {
	mInfoTextView.setText("Можно кормить кота");
}

Теперь программа работает без краха. Как только Java увидела, что первое выражение возвращает false, то второе выражение с делением просто игнорируется.

Сокращённые варианты операторов AND и OR принято использовать в тех ситуациях, когда требуются операторы булевой логики, а их односимвольные родственники используются для побитовых операций.

Тернарный оператор

В языке Java есть также специальный тернарный условный оператор, которым можно заменить определённые типы операторов if-then-else — это оператор ?:

Тернарный оператор использует три операнда. Выражение записывается в следующей форме:


логическоеУсловие ? выражение1 : выражение2

Если логическоеУсловие равно true, то вычисляется выражение1 и его результат становится результатом выполнения всего оператора. Если же логическоеУсловие равно false, то вычисляется выражение2, и его значение становится результатом работы оператора. Оба операнда выражение1 и выражение2 должны возвращать значение одинакового (или совместимого) типа.

Рассмотрим пример, в котором переменной absval присваивается абсолютное значение переменной val.

int absval, val;
val = 5;
absval = val < 0 ? -val : val;

// выводим число
mInfoTextView.setText("" + absval);

val = -5;
absval = val < 0 ? -val : val;

mInfoTextView.setText("" + absval);

Переменной absval будет присвоено значение переменной val, если значение больше или равно нулю (вторая часть выражения). Если значение переменной val отрицательное, то переменной absval присваивается значение переменной, взятое со знаком минус, в результате минус на минус даст плюс, то есть положительно значение. Перепишем код с использованием if-else:

if(val < 0) absval = -val;
else absval = val;

Другой пример с тернарным оператором можете посмотреть здесь.

Реклама

Logical operators are used to performing logical “AND”, “OR” and “NOT” operations, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is, while using AND operator, the second condition is not evaluated if the first one is false. Whereas while using OR operator, the second condition is not evaluated if the first one is true, i.e. the AND and OR operators have a short-circuiting effect. Used extensively to test for several conditions for making a decision.

  1. AND Operator ( && ) – if( a && b ) [if true execute else don’t]
  2. OR Operator ( || ) – if( a || b) [if one of them is true execute else don’t]
  3. NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]

Example For Logical Operator in Java

Here is an example depicting all the operators where the values of variables a, b, and c are kept the same for all the situations.

a = 10, b = 20, c = 30

For AND operator:

Condition 1: c > a                 
Condition 2: c > b         

Output: True [Both Conditions are true]  

For OR Operator:    

Condition 1: c > a 
Condition 2: c > b  

Output: True [One of the Condition if true]

For NOT Operator:
Condition 1: c > a
Condition 2: c > b

Output: False [Because the result was true and NOT operator did it's opposite]

1. Logical ‘AND’ Operator (&&) 

This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. In Simple terms, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero). 

Syntax:

condition1 && condition2

Illustration:

a = 10, b = 20, c = 20

condition1: a < b
condition2: b == c

if(condition1 && condition2)
d = a + b + c

// Since both the conditions are true
d = 50.

Example

Java

import java.io.*;

class Logical {

    public static void main(String[] args)

    {

        int a = 10, b = 20, c = 20, d = 0;

        System.out.println("Var1 = " + a);

        System.out.println("Var2 = " + b);

        System.out.println("Var3 = " + c);

        if ((a < b) && (b == c)) {

            d = a + b + c;

            System.out.println("The sum is: " + d);

        }

        else

            System.out.println("False conditions");

    }

}

Output

Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50

Now in the below example, we can see the short-circuiting effect. Here when the execution reaches to if statement, the first condition inside the if statement is false and so the second condition is never checked. Thus the ++b(pre-increment of b) never happens and b remains unchanged.

Example:

Java

import java.io.*;

class shortCircuiting {

    public static void main(String[] args)

    {

        int a = 10, b = 20, c = 15;

        System.out.println("Value of b : " + b);

        if ((a > c) && (++b > c)) {

            System.out.println("Inside if block");

        }

        System.out.println("Value of b : " + b);

    }

}

Output:

AND Operator Output

The output of AND Operator 

2. Logical ‘OR’ Operator (||) 

This operator returns true when one of the two conditions under consideration is satisfied or is true. If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false. 

Syntax:

condition1 || condition2

Example:

a = 10, b = 20, c = 20

condition1: a < b
condition2: b > c

if(condition1 || condition2)
d = a + b + c

// Since one of the condition is true
d = 50.

Java

import java.io.*;

class Logical {

    public static void main(String[] args)

    {

        int a = 10, b = 1, c = 10, d = 30;

        System.out.println("Var1 = " + a);

        System.out.println("Var2 = " + b);

        System.out.println("Var3 = " + c);

        System.out.println("Var4 = " + d);

        if (a > b || c == d)

            System.out.println("One or both + the conditions are true");

        else

            System.out.println("Both the + conditions are false");

    }

}

Output

Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true

Now in the below example, we can see the short-circuiting effect for OR operator. Here when the execution reaches to if statement, the first condition inside the if statement is true and so the second condition is never checked. Thus the ++b (pre-increment of b) never happens and b remains unchanged.

Example

Java

import java.io.*;

class ShortCircuitingInOR {

    public static void main (String[] args) {

        int a = 10, b = 20, c = 15;

        System.out.println("Value of b: " +b);

        if((a < c) || (++b < c))

            System.out.println("Inside if");

        System.out.println("Value of b: " +b);

    }

}

Output

Value of b: 20
Inside if
Value of b: 20

3. Logical ‘NOT’ Operator (!)

Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the condition is true, the operation returns false. 

Syntax:

!(condition)

Example:

a = 10, b = 20

!(a<b) // returns false
!(a>b) // returns true

Java

import java.io.*;

class Logical {

    public static void main(String[] args)

    {

        int a = 10, b = 1;

        System.out.println("Var1 = " + a);

        System.out.println("Var2 = " + b);

        System.out.println("!(a < b) = " + !(a < b));

        System.out.println("!(a > b) = " + !(a > b));

    }

}

Output

Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false

4. Implementing all logical operators on Boolean values (By default values – TRUE or FALSE)

Syntax – 

 boolean a = true;
 boolean b = false;

program –

Java

public class LogicalOperators {

    public static void main(String[] args) {

        boolean a = true;

        boolean b = false;

        System.out.println("a: " + a);

        System.out.println("b: " + b);

        System.out.println("a && b: " + (a && b));

        System.out.println("a || b: " + (a || b));

        System.out.println("!a: " + !a);

        System.out.println("!b: " + !b);

    }

}

Output

a: true
b: false
a && b: false
a || b: true
!a: false
!b: true

Explanation:

  • The code above is a Java program that implements all logical operators with default values. The program defines a class LogicalOperators with a main method.
  • In the main method, two boolean variables a and b are defined and assigned default values true and false, respectively.
  • The program then prints the values of a and b to the console using the System.out.println method. This allows us to verify the values assigned to a and b.
  • Next, the program calculates the result of the logical operators && (and), || (or), and ! (not) applied to a and b. The results of these operations are also printed to the console using the System.out.println method.
  • The && operator returns true if both operands are true; otherwise, it returns false. In this case, the result of a && b is false.
  • The || operator returns true if either operand is true; otherwise, it returns false. In this case, the result of a || b is true.
  • The ! operator negates the value of its operand. If the operand is true, the result is false, and if the operand is false, the result is true. In this case, the results of !a and !b are false and true, respectively.
  • The output of the program shows the truth table for all logical operators. This table provides a visual representation of how these operators behave for all possible combinations of true and false inputs.

5. Advantages of logical operators:

The advantages of using logical operators in a program include:

  1. Readability: Logical operators make code more readable by providing a clear and concise way to express complex conditions. They are easily recognizable and make it easier for others to understand the code.
  2. Flexibility: Logical operators can be combined in various ways to form complex conditions, making the code more flexible. This allows developers to write code that can handle different scenarios and respond dynamically to changes in the program’s inputs.
  3. Reusability: By using logical operators, developers can write code that can be reused in different parts of the program. This reduces the amount of code that needs to be written and maintained, making the development process more efficient.
  4. Debugging: Logical operators can help to simplify the debugging process. If a condition does not behave as expected, it is easier to trace the problem by examining the results of each logical operator rather than having to navigate through a complex code structure.

Overall, logical operators are an important tool for developers and play a crucial role in the implementation of complex conditions in a program. They help to improve the readability, flexibility, reusability, and debuggability of the code.

Logical operators are used to performing logical “AND”, “OR” and “NOT” operations, i.e. the function similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consideration. One thing to keep in mind is, while using AND operator, the second condition is not evaluated if the first one is false. Whereas while using OR operator, the second condition is not evaluated if the first one is true, i.e. the AND and OR operators have a short-circuiting effect. Used extensively to test for several conditions for making a decision.

  1. AND Operator ( && ) – if( a && b ) [if true execute else don’t]
  2. OR Operator ( || ) – if( a || b) [if one of them is true execute else don’t]
  3. NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]

Example For Logical Operator in Java

Here is an example depicting all the operators where the values of variables a, b, and c are kept the same for all the situations.

a = 10, b = 20, c = 30

For AND operator:

Condition 1: c > a                 
Condition 2: c > b         

Output: True [Both Conditions are true]  

For OR Operator:    

Condition 1: c > a 
Condition 2: c > b  

Output: True [One of the Condition if true]

For NOT Operator:
Condition 1: c > a
Condition 2: c > b

Output: False [Because the result was true and NOT operator did it's opposite]

1. Logical ‘AND’ Operator (&&) 

This operator returns true when both the conditions under consideration are satisfied or are true. If even one of the two yields false, the operator results false. In Simple terms, cond1 && cond2 returns true when both cond1 and cond2 are true (i.e. non-zero). 

Syntax:

condition1 && condition2

Illustration:

a = 10, b = 20, c = 20

condition1: a < b
condition2: b == c

if(condition1 && condition2)
d = a + b + c

// Since both the conditions are true
d = 50.

Example

Java

import java.io.*;

class Logical {

    public static void main(String[] args)

    {

        int a = 10, b = 20, c = 20, d = 0;

        System.out.println("Var1 = " + a);

        System.out.println("Var2 = " + b);

        System.out.println("Var3 = " + c);

        if ((a < b) && (b == c)) {

            d = a + b + c;

            System.out.println("The sum is: " + d);

        }

        else

            System.out.println("False conditions");

    }

}

Output

Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50

Now in the below example, we can see the short-circuiting effect. Here when the execution reaches to if statement, the first condition inside the if statement is false and so the second condition is never checked. Thus the ++b(pre-increment of b) never happens and b remains unchanged.

Example:

Java

import java.io.*;

class shortCircuiting {

    public static void main(String[] args)

    {

        int a = 10, b = 20, c = 15;

        System.out.println("Value of b : " + b);

        if ((a > c) && (++b > c)) {

            System.out.println("Inside if block");

        }

        System.out.println("Value of b : " + b);

    }

}

Output:

AND Operator Output

The output of AND Operator 

2. Logical ‘OR’ Operator (||) 

This operator returns true when one of the two conditions under consideration is satisfied or is true. If even one of the two yields true, the operator results true. To make the result false, both the constraints need to return false. 

Syntax:

condition1 || condition2

Example:

a = 10, b = 20, c = 20

condition1: a < b
condition2: b > c

if(condition1 || condition2)
d = a + b + c

// Since one of the condition is true
d = 50.

Java

import java.io.*;

class Logical {

    public static void main(String[] args)

    {

        int a = 10, b = 1, c = 10, d = 30;

        System.out.println("Var1 = " + a);

        System.out.println("Var2 = " + b);

        System.out.println("Var3 = " + c);

        System.out.println("Var4 = " + d);

        if (a > b || c == d)

            System.out.println("One or both + the conditions are true");

        else

            System.out.println("Both the + conditions are false");

    }

}

Output

Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true

Now in the below example, we can see the short-circuiting effect for OR operator. Here when the execution reaches to if statement, the first condition inside the if statement is true and so the second condition is never checked. Thus the ++b (pre-increment of b) never happens and b remains unchanged.

Example

Java

import java.io.*;

class ShortCircuitingInOR {

    public static void main (String[] args) {

        int a = 10, b = 20, c = 15;

        System.out.println("Value of b: " +b);

        if((a < c) || (++b < c))

            System.out.println("Inside if");

        System.out.println("Value of b: " +b);

    }

}

Output

Value of b: 20
Inside if
Value of b: 20

3. Logical ‘NOT’ Operator (!)

Unlike the previous two, this is a unary operator and returns true when the condition under consideration is not satisfied or is a false condition. Basically, if the condition is false, the operation returns true and when the condition is true, the operation returns false. 

Syntax:

!(condition)

Example:

a = 10, b = 20

!(a<b) // returns false
!(a>b) // returns true

Java

import java.io.*;

class Logical {

    public static void main(String[] args)

    {

        int a = 10, b = 1;

        System.out.println("Var1 = " + a);

        System.out.println("Var2 = " + b);

        System.out.println("!(a < b) = " + !(a < b));

        System.out.println("!(a > b) = " + !(a > b));

    }

}

Output

Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false

4. Implementing all logical operators on Boolean values (By default values – TRUE or FALSE)

Syntax – 

 boolean a = true;
 boolean b = false;

program –

Java

public class LogicalOperators {

    public static void main(String[] args) {

        boolean a = true;

        boolean b = false;

        System.out.println("a: " + a);

        System.out.println("b: " + b);

        System.out.println("a && b: " + (a && b));

        System.out.println("a || b: " + (a || b));

        System.out.println("!a: " + !a);

        System.out.println("!b: " + !b);

    }

}

Output

a: true
b: false
a && b: false
a || b: true
!a: false
!b: true

Explanation:

  • The code above is a Java program that implements all logical operators with default values. The program defines a class LogicalOperators with a main method.
  • In the main method, two boolean variables a and b are defined and assigned default values true and false, respectively.
  • The program then prints the values of a and b to the console using the System.out.println method. This allows us to verify the values assigned to a and b.
  • Next, the program calculates the result of the logical operators && (and), || (or), and ! (not) applied to a and b. The results of these operations are also printed to the console using the System.out.println method.
  • The && operator returns true if both operands are true; otherwise, it returns false. In this case, the result of a && b is false.
  • The || operator returns true if either operand is true; otherwise, it returns false. In this case, the result of a || b is true.
  • The ! operator negates the value of its operand. If the operand is true, the result is false, and if the operand is false, the result is true. In this case, the results of !a and !b are false and true, respectively.
  • The output of the program shows the truth table for all logical operators. This table provides a visual representation of how these operators behave for all possible combinations of true and false inputs.

5. Advantages of logical operators:

The advantages of using logical operators in a program include:

  1. Readability: Logical operators make code more readable by providing a clear and concise way to express complex conditions. They are easily recognizable and make it easier for others to understand the code.
  2. Flexibility: Logical operators can be combined in various ways to form complex conditions, making the code more flexible. This allows developers to write code that can handle different scenarios and respond dynamically to changes in the program’s inputs.
  3. Reusability: By using logical operators, developers can write code that can be reused in different parts of the program. This reduces the amount of code that needs to be written and maintained, making the development process more efficient.
  4. Debugging: Logical operators can help to simplify the debugging process. If a condition does not behave as expected, it is easier to trace the problem by examining the results of each logical operator rather than having to navigate through a complex code structure.

Overall, logical operators are an important tool for developers and play a crucial role in the implementation of complex conditions in a program. They help to improve the readability, flexibility, reusability, and debuggability of the code.

Логические операторы языка Java выполняются только с операндами типа boolean.

Следующая таблица перечисляет логические операторы языка Java:

Операция     Описание
& Логическая операция И (AND) или конъюнкция
| Логическая операция ИЛИ (OR) или дизъюнкция
^ Логическая операция исключающее ИЛИ (XOR)
! Логическая унарная операция НЕ (NOT)
|| Укороченная логическая операция ИЛИ (short-circuit)
&& Укороченная логическая операция И (short-circuit)
== Равенство
!= Неравенство
&= Логическая операция И с присваиванием
|= Логическая операция ИЛИ с присваиванием
^= Логическая операция исключающее ИЛИ с присваиванием

1. Логические операторы OR, AND, XOR, NOT.

Начнем с операций OR(|), AND(&), XOR(^), NOT(!). Операторы OR, AND, XOR являются бинарными — они требуют два оператора. NOT — это унарный оператор, только один оператор участвует в операции. Результаты выполнения этих логических операций представлены в следующей таблице:

A     B A|B A&B
A^B
!A
false false false false false true
true false true false true false
false true true false true true
true true true true false false

OR (|) — результат будет true, если хотя бы одно значение равно trueПример: для того, чтобы забрать ребенка из садика, должна прийти либо мать, либо отец, либо оба — в любом случае результат будет положительный. Если же никто не придет, ребенка не заберут — результат будет отрицательный.

AND (&) — результат будет true, только если и A, и B равны true. Пример: для того чтобы свадьба состоялась, и невеста (A) и жених (B) должны явиться на бракосочетание, иначе оно не состоится.

XOR (^) — результат будет true, только если или A равно true, или В равно true. Пример: у двух друзей на двоих один велосипед, поездка на велосипеде состоится только если один из них поедет на нем. Вдвоем они ехать не могут. 

NOT (!) — инвертирование значения. Если значение было true, то станет false, и наоборот.

Рассмотрим пример использования логических операторов:

public class BooleanLogic1 {
    public static void main(String[] args) {
        boolean a = true;
        boolean b = false;
        boolean c = a | b;
        boolean d = a & b;
        boolean e = a ^ b;
        boolean f = (!a & b) | (a & !b);
        boolean g = !a;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("a | b = " + c);
        System.out.println("a & b = " + d);
        System.out.println("a ^ b = " + e);
        System.out.println("(!a & b) | (a & !b) = " + f);
        System.out.println("!a = " + g);
    }
}

Чаще всего в языке Java используются так называемые укороченные логические операторы (short-circuit):

||   —  Укороченный логический оператор ИЛИ

&&  — Укороченный логический оператор И

Правый операнд сокращенных операций вычисляется только в том случае, если от него зависит результат операции, то есть если левый операнд конъюнкции имеет значение true, или левый операнд дизъюнкции имеет значение false.

В формальной спецификации языка Java укороченные логические операции называются условными.

В следующем примере правый операнд логического выражения вычисляться не будет, так как условие d!=0 не выполняется и нет смысла дальше вычислять это выражение:

public class BooleanLogic2 {
    public static void main(String[] args) {
        int d = 0;
        int num = 10;
        if (d != 0 && num / d > 10) {
            System.out.println("num = " + num);
        }
    }
}

Если же логическое выражение переписать как d != 0 & num / d > 10, то правое выражение вычисляться будет. И в этом случае программа выбросит исключение времени выполнения с сообщением — на ноль делить нельзя.

Если нам надо сравнить возможный диапазон значений для какой-то переменной, например — a<x<b, такое условие разбивается на два: a<x &&x<b:

public class BooleanLogic3 {
    public static void main(String[] args) {
        int a = 1;
        int b = 2;
        int x = 3;
        System.out.print(a < x && x < b);
       // System.out.print(a < x < b);//Ошибка компиляции
    }
}

Здесь все просто — чтобы сравнить два значения типа boolean, можно использовать знаки == (проверка на равенство) и != (проверка на неравенство):

public class BooleanLogic4 {
    public static void main(String[] args) {
        boolean b1 = true;
        boolean b2 = false;
        System.out.println(b1 == b2);
        System.out.println(b1 != b2);
    }
}

Также существуют операции с присваиванием для AND, OR, XOR. Посмотрим пример:

public class BooleanLogic5 {
    public static void main(String[] args) {
        boolean b1 = true;
        boolean b2 = true;
        b1 &= b2;//равносильно b1 = b1 & b2;
        System.out.println(b1);
        b1 |= b2; //равносильно b1 = b1 | b2;
        System.out.println(b1);
        b1 ^= b2; //равносильно b1 = b1 ^ b2;
        System.out.println(b1);
    }
}

Презентацию с видео можно скачать на Patreon.

Logical Operators

In this chapter you will learn:Logical Operators

  1. What is logical/Conditional operator in Java?
  2. Logical operator symbol
  3. Programming example

What is logical operator in Java?

Logical operator is also known as conditional operator in java. It is And (&&), Or(||) andNot(!). The logical operator is very useful when you need to compare two statements.

Operator Description Example
&& Conditional-AND – Compare two statement and return true if both are true if(username==”user1″ && password==”pass123″)
|| Conditional-OR – compare two statement and return true if one of them is true if(username==”user1″ || password==”pass123″)
?: Ternary (shorthand for if-then-else statement) variable x = (expression) ? value if true : value if false

You can understand the working of logical or conditional operator using this programming example:

Programming Example:

class LogicalOperator
{
  public static void main(String[] args)
  {
    String username, password;
    username="user1";
    password="pass123";
    
    if(username=="user1" && password=="pass123")
    {
      System.out.println("Authorized Login Successful");
    }
    else if(username=="user1" && password!="pass123")
    {
      System.out.println("Incorrect Password");
    }
    else if(username!="user1" && password=="pass123")
    {
      System.out.println("User Not Registered");
    }
    else
    {
      System.out.println("Incorrect UserID and Password");
    }      
  }
}

Output

D:JavaProgram>javac LogicalOperator.java

D:JavaProgram>java LogicalOperator
Authorized Login Successful

D:JavaProgram> __

Summary

In this chapter you have learned what is logical operator or conditional operator in Java. Mostly And(&&), Or(||) and Not(!) is considered as logical operator in Java. In the next chapter you will learn about Ternary Operator in Java.

Learn with Fun

Понравилась статья? Поделить с друзьями:
  • Is a pen little it как правильно написать
  • Ios или ios как правильно пишется
  • Inshaallah как пишется
  • Info amefir tv как написать письмо
  • Inc как пишется