Presentation is loading. Please wait.

Presentation is loading. Please wait.

Logical OperatorstMyn1 Logical Operators Using logical operators, we can combine a series of comparisons into a single expression. if(letter>=‘A’ && letter<=‘Z’)

Similar presentations


Presentation on theme: "Logical OperatorstMyn1 Logical Operators Using logical operators, we can combine a series of comparisons into a single expression. if(letter>=‘A’ && letter<=‘Z’)"— Presentation transcript:

1 Logical OperatorstMyn1 Logical Operators Using logical operators, we can combine a series of comparisons into a single expression. if(letter>=‘A’ && letter<=‘Z’) System.out.println(“This is an upper case letter”); if(income>=100000 || capital>=1000000) System.out.println(“Why do you want to borrow?”);

2 Logical OperatorstMyn2 The logical operators OperatorMeaning &AND |OR ^XOR(exclusive OR) ||Short-circuit OR &&Short-circuit AND !NOT

3 Logical OperatorstMyn3 Let’s demonstrate the difference between the Short- circuit AND (&&) and the normal AND (&). In the first example with the normal AND operator both expressions are evaluated, allowing a division by zero to occur:

4 Logical OperatorstMyn4 package logical; public class Main { public static void main(String[] args) { int n=10, d=0; if(d!=0 & (n%d)==0) System.out.println(d+" is a factor of "+n); } run: Exception in thread "main" java.lang.ArithmeticException: / by zero at logical.Main.main(Main.java:8) Java Result: 1 BUILD SUCCESSFUL (total time: 1 second)

5 Logical OperatorstMyn5 In the next example with the short-circuit AND a division by zero has been prevented:

6 Logical OperatorstMyn6 package logicalshortcircuit; public class Main { public static void main(String[] args) { int n=10, d=0; if(d!=0 && (n%d)==0) System.out.println(d+" is a factor of "+n); } run: BUILD SUCCESSFUL (total time: 0 seconds)

7 Logical OperatorstMyn7 Next example demonstrates the usage of the NOT operator:

8 Logical OperatorstMyn8 package logical1; public class Main { public static void main(String[] args) { int num1=15, num2=16; if(!(num1==num2)) System.out.println("The numbers are not of equal size."); else System.out.println("The numbers were of equal size."); } run: The numbers are not of equal size. BUILD SUCCESSFUL (total time: 0 seconds)

9 Logical OperatorstMyn9 Exclusive OR operator is only seldom (?) seen:

10 Logical OperatorstMyn10 package logical2; public class Main { public static void main(String[] args) { int num1=12, num2=13; if(num1==12 ^ num2==14) System.out.println("Yes, exactly ONE and ONLY ONE " + "operand was TRUE."); } run: Yes, exactly ONE and ONLY ONE operand was TRUE. BUILD SUCCESSFUL (total time: 0 seconds)


Download ppt "Logical OperatorstMyn1 Logical Operators Using logical operators, we can combine a series of comparisons into a single expression. if(letter>=‘A’ && letter<=‘Z’)"

Similar presentations


Ads by Google