带有示例的Java逻辑运算符
运算符构成任何编程语言的基本构建块。 Java也提供了许多类型的运算符,可以根据需要执行各种计算和功能,如逻辑、算术、关系等。它们根据它们提供的功能进行分类。这里有几种类型:
- 算术运算符
- 一元运算符
- 赋值运算符
- 关系运算符
- 逻辑运算符
- 三元运算符
- 位运算符
- 移位运算符
本文解释了有关逻辑运算符的所有知识。
逻辑运算符
这些运算符用于执行逻辑“与”、“或”和“非”运算,即类似于数字电子学中的与门和或门的函数。它们用于组合两个或多个条件/约束或补充在特定考虑下对原始条件的评估。要记住的一件事是,如果第一个条件为假,则不会评估第二个条件,即它具有短路效应。广泛用于测试做出决定的几个条件。让我们详细了解每个逻辑运算符:
- “逻辑与”运算符(&&):当考虑的两个条件都满足或为真时,此运算符返回真。如果两者之一产生假,则运算符的结果为假。例如,当 cond1 和 cond2 都为真(即非零)时, cond1 && cond2 返回真。
句法:condition1 && condition2
例子:
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.
// Java code to illustrate // logical AND operator import java.io.*; class Logical { public static void main(String[] args) { // initializing variables int a = 10, b = 20, c = 20, d = 0; // Displaying a, b, c System.out.println("Var1 = " + a); System.out.println("Var2 = " + b); System.out.println("Var3 = " + c); // using logical AND to verify // two constraints if ((a < b) && (b == c)) { d = a + b + c; System.out.println("The sum is: " + d); } else System.out.println("False conditions"); } }
输出:Var1 = 10 Var2 = 20 Var3 = 20 The sum is: 50
- “逻辑或”运算符(||):当考虑的两个条件之一满足或为真时,此运算符返回真。如果两者中的任何一个都为真,则运算符的结果为真。要使结果为假,两个约束都需要返回假。
句法:condition1 || condition2
例子:
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 code to illustrate // logical OR operator import java.io.*; class Logical { public static void main(String[] args) { // initializing variables int a = 10, b = 1, c = 10, d = 30; // Displaying a, b, c System.out.println("Var1 = " + a); System.out.println("Var2 = " + b); System.out.println("Var3 = " + c); System.out.println("Var4 = " + d); // using logical OR to verify // two constraints if (a > b || c == d) System.out.println("One or both" + " the conditions are true"); else System.out.println("Both the" + " conditions are false"); } }
输出:Var1 = 10 Var2 = 1 Var3 = 10 Var4 = 30 One or both the conditions are true
- “逻辑非”运算符(!):与前两个不同,这是一个一元运算运算符,当考虑的条件不满足或为假条件时返回真。基本上,如果条件为假,则操作返回真,当条件为真时,操作返回假。
句法:
!(condition)
例子:
a = 10, b = 20 !(ab) // returns true
// Java code to illustrate // logical NOT operator import java.io.*; class Logical { public static void main(String[] args) { // initializing variables int a = 10, b = 1; // Displaying a, b, c System.out.println("Var1 = " + a); System.out.println("Var2 = " + b); // Using logical NOT operator System.out.println("!(a < b) = " + !(a < b)); System.out.println("!(a > b) = " + !(a > b)); } }
输出:Var1 = 10 Var2 = 1 !(a < b) = true !(a > b) = false