Not operation in 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 . Пример: для того, чтобы забрать ребенка из садика, должна прийти либо мать, либо отец, либо оба — в любом случае результат будет положительный. Если же никто не придет, ребенка не заберут — результат будет отрицательный.

Читайте также:  Php глобальный объект класса

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 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: Negation, Bitwise Not, and Boolean Not

Book image

There are two types of unary operations in Java that you should view together so that you don’t misunderstand them later on. Negation is the act of setting a value to its negative version — the value of 2 becomes –2.

Some math-related tasks require that you negate a value in order to use it. In some cases, people confuse negation with subtraction, but subtraction is a binary operation and negation is a unary operation.

Negation is the act of setting a value to its negative equivalent. A value of 2 becomes –2.

Contrast negation with the bitwise Not operation, which you implement by using the ~ operator. The Not operation reverses each of the bits in a value. All of the 0s become 1s and vice versa. The Not operation is often used in Boolean-related tasks. It helps an application consider the logic of a task.

The term bitwise means to perform a task a single bit at a time, rather than using the entire value. So, a bitwise Not operation looks at each bit individually — any 1 becomes a 0, and vice versa. Consequently, when you have a value of 5, which in binary is 00000101, it becomes a negative six, which in binary is 11111010. Notice how the bits are precisely reversed in value.

To make things even more confusing, there’s a second Not operation called a Boolean Not operation that works on Boolean values. This operation relies on the ! operator. The bitwise operator (~) won’t work on Boolean values and the logical operator (!) won’t work on values other than Boolean.

Boolean values are either true or false. When you Not a Boolean value, you turn it from true to false, or from false to true.

Источник

Logical Operators in Java

Logical-Operators-in-Java

Logical operators are used for performing the operations on one or two variables for evaluating and retrieving the logical outcome. Typically, the return value for logical operations is in boolean format and is applied in a program to establish better control in the program’s execution flow. In Java, the logical operators used are ‘&’ for performing AND operation, ‘|’ for OR operation, ‘!’ for NOT operation, and ‘^’ for XOR operation.

Features of Logical Operators in Java

  • Logical operators are used to controlling the flow of execution.
  • Boolean logical operators always return a Boolean value.
  • These operators are applied to one or more Boolean operands.
  • Java provides 4 logical operators “&”,”|”,”!”or”~” and “^”.

Let’s consider the following table for the result of each operation on a specific input.

Web development, programming languages, Software testing & others

A B A&B A|B A^B !A or ~A
True (1) True(1) True (1) True(1) False (0) False (0)
True(1) False(0) False(0) True(1) True(1) False(0)
False(0) True(1) False(0) True(1) True(1) True(1)
False(0) False(0) False(0) False(0) False(0) True(1)

Different Logical Operators in Java with Description

The following table shows the operator and its description.

Operator Meaning Description
& Logical AND If both the inputs are True, then the result is True; if anyone input is False, the result will be False.
| Logical OR The result is True if any of the input is True. The result will be false if both the inputs are False.
! or ~ Logical NOT Logical NOT is a unary operator; it operates only on a single operand. It always outputs the negation of input value.
^ Logical XOR The result is True if any one of the input is True. The result will be false if both the inputs are the Same.

1. Logical AND Operator “&”

The logical “&” operator performs the digital AND operation. This operator works on two Boolean operands, and the result will be Boolean. AND operator represented by the symbol “&” or “&&” i.e. short circuit AND operation.

Note: in simple & operation, it checks both operands’ values, i.e. Operand1 & Operand 2. In short circuit AND operation && it checks the value of the first Operand1 later it will go with the value of operand 2 if and only if operand 1 value is true.

Operand1 and Operand2 are any Boolean values.

  1. True: the result is True if and only if both operand values are True.
  2. False: the result is False when any one of the operand values is false. And if both values are False.

Truth Table of AND:

A B A & B
FALSE (0) FALSE (0) FALSE (0)
FALSE (0) TRUE (1) FALSE (0)
TRUE (1) FALSE (0) FALSE (0)
TRUE (1) TRUE (1) TRUE (1)
Example of AND Operator
package com.java.demo; public class DemoAND < public static void main(String[] args) < boolean a=true; boolean b=false; int num1=0; int num2=1; boolean out1=(a & a); boolean out2=(a & b); boolean out3=(b & a); boolean out4=(b & b); System.out.println("True & True :"+out1); System.out.println("True & False :"+out2); System.out.println("False & True :"+out3); System.out.println("False & False :"+out4); if(num1 ==0 & num2 == 1) < System.out.println("The Condition is True. "); >> >

Logical Operators in Java 1-1

2. Logical OR Operator “ |.”

Logical OR operator in java is used to perform actual digital OR operations in java. This operator is used with two Boolean operands, and the result will be Boolean, i.e. true or False. In java, the Logical OR operator is represented with the symbol “|” (Simple OR) or “||” (Short Circuit OR).

Note: Java uses two Logical OR operations, simple OR – “|” and Short circuit OR – “||”.in simple logical OR operation, both operand values are checked, and depending on the values it gives the result.in Short Circuit OR operation “||” it checks the value of the first operand, i.e. Operand1, and then checks the value of the second operand, i.e. operand2 either operand1 value is true or false.

Operand1 and Operand2 are any Boolean values.

  • True: If both operand values are True. Suppose anyone Operand value is True.
  • False: If both operand values are False.

Truth Table of OR:

A B A |B
FALSE (0) FALSE (0) FALSE (0)
FALSE (0) TRUE (1) TRUE (1)
TRUE (1) FALSE (0) TRUE (1)
TRUE (1) TRUE (1) TRUE (1)
Example of OR Operator
package com.java.demo; public class DemoOR < public static void main(String[] args) < boolean a=true; boolean b=false; int num=0; boolean out1=(a | a); boolean out2=(a | b); boolean out3=(b | a); boolean out4=(b | b); System.out.println("True | True :"+out1); System.out.println("True | False :"+out2); System.out.println("False | True :"+out3); System.out.println("False | False :"+out4); if(num == 0 | num == 1) < System.out.println("The Number is binary.."); >> >

Logical Operators in Java 1-2

3. Logical NOT Operator “!” or “ ~.”

Logical NOT operator performs actual digital NOT operation in java, i.e. Negation of Input value. This logical operator is a Unary Logical operator; it is used with only one operand.in java Logical NOT operator is represented by the symbol “!” or “ ~ ”.simple use of! The operator is to negating the input value. For example, input, True make it False or if the input is False to make it True.

Operand holds any Boolean value. Condition is any Boolean value, i.e. Result of any Logical operation.

  • True: The result is True if the input value is False.
  • False: The result is False if input values are True.

Truth Table of NOT:

A !A
FALSE (0) TRUE (1)
TRUE (1) FALSE (0)
Example of NOT Operator

NOT Operator

4. Logical XOR Operator “ ^.”

Logical XOR operator is a short form of Exclusive OR operator. This logical operator is when we have to check or compare the values of anyone operand is True then the output is true. In Java, Logical XOR is represented by the symbol “ ^ ”.This operator is Binary Logical Operator, i.e. can be used with two operands/conditions. Output this operator is also a Boolean value.

Operand1 ^ Operand2 or Condition1 ^ Condition2

Operand1 and Operand2 hold any Boolean values. Condition1 and Condition2 hold any Boolean values, i.e. output any logical operation.

  • True: The result is True if any one of the input is True.
  • False: The result is False if both the inputs are the Same.

Truth Table of XOR:

A B A ^ B
FALSE (0) FALSE (0) FALSE (0)
FALSE (0) TRUE (1) TRUE (1)
TRUE (1) FALSE (0) TRUE (1)
TRUE (1) TRUE (1) FALSE (0)
Example of XOR Operator

XOR Operator

Conclusion

It makes java code more powerful and flexible. Use logical operators in conditional statements or looping statements to look very clean. The most important benefit of the logical operator is it reduces the code complexity. For example, it reduces the number of if…else conditional statements. This indirectly benefits in code compilation, run time etc.…overall code performance is increased.

This is a guide to Logical Operators in Java. Here we discuss the introduction and different logical operators in java, i.e. AND, OR, NOT, XOR with Examples. You may also look at the following articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Logical Operators in Java

Book image

A logical operator (sometimes called a “Boolean operator”) in Java programming is an operator that returns a Boolean result that’s based on the Boolean result of one or two other expressions.

Sometimes, expressions that use logical operators are called “compound expressions” because the effect of the logical operators is to let you combine two or more condition tests into a single expression.

Operator Name Type Description
! Not Unary Returns true if the operand to the right evaluates to false . Returns false if the operand to the right is true .
& And Binary Returns true if both of the operands evaluate to true . Both operands are evaluated before the And operator is applied.
| Or Binary Returns true if at least one of the operands evaluates to true . Both operands are evaluated before the Or operator is applied.
^ Xor Binary Returns true if one — and only one — of the operands evaluates to true . Returns false if both operands evaluate to true or if both operands evaluate to false .
&& Conditional And Binary Same as & , but if the operand on the left returns false , it returns false without evaluating the operand on the right.
|| Conditional Or Binary Same as | , but if the operand on the left returns true , it returns true without evaluating the operand on the right .

Источник

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