Логические операторы в программировании java

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

Логические операторы языка 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 . Пример: у двух друзей на двоих один велосипед, поездка на велосипеде состоится только если один из них поедет на нем. Вдвоем они ехать не могут.

Читайте также:  Php get apache env

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 header3">2. Укороченные логические операторы (short-circuit). 

Чаще всего в языке 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 language-java">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);//Ошибка компиляции >>

3. Операции ==, !=.

Здесь все просто - чтобы сравнить два значения типа 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); >>

4. Операции с присваиванием.

Также существуют операции с присваиванием для 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 .

Источник

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

Ihechikara Vincent Abba

Ihechikara Vincent Abba

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 bitwise AND 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

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:

So let's carry out the operation.

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

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

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

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

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.

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.

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.

Источник

Оцените статью