Logical operators

Intermediate Java

Jim White

Java Developer

ARE, OR, and NOT

  • Logical operators allow combining of multiple conditions in one statement
  • Three main ones:
    • AND
    • OR
    • NOT
Intermediate Java

AND

  • Checks if both conditions are true
boolean isLoggedIn = true;
boolean isAdmin = true;

// Both are true
if (isLoggedIn && isAdmin) {
  System.out.println("Welcome admin!");
} else {
  System.out.println("You shall not pass.");
}
Welcome admin!
  • If at least one is false, && returns false
boolean isLoggedIn = false;
boolean isAdmin = true;

// Only one is true, so else is executed
if (isLoggedIn && isAdmin) {
  System.out.println("Welcome admin!");
} else {
  System.out.println("You shall not pass.");
}
You shall not pass.
Intermediate Java

OR

  • Checks if either condition is true
boolean isAdmin = true;
boolean isModerator = false;

// Only one condition is true
if (isAdmin || isModerator) {
  System.out.println("Welcome!");
} else {
  System.out.println("You shall not pass.");
}
Welcome!
  • true if either or both conditions are true
boolean isAdmin = true;
boolean isModerator = true;

// Both conditions are true
if (isAdmin || isModerator) {
  System.out.println("Welcome!");
} else {
  System.out.println("You shall not pass.");
}
Welcome!
Intermediate Java

NOT

  • Flips true to false and false to true
boolean isLoggedIn = false;

// isLoggedIn is false, so !isLoggedIn is true
if (!isLoggedIn) {
    System.out.println("You need to log in!");
} else {
    System.out.println("You are logged in, continue!");
}
You need to log in!
Intermediate Java

Logical operators and if-else if-else

int score = 90;
boolean isAttending = false;

if (score > 80 && isAttending) {
  System.out.println("Excellent work!");
} else if (score > 80 && !isAttending) {
  System.out.println("Good work, but attendance is important.");
} else if (score <= 80 && isAttending) {
  System.out.println("You need to work harder.");
} else {
  System.out.println("You need to work harder and attend classes.");
}
Good work, but attendance is important.
Intermediate Java

Recap

The following table summarizes the values for &&, ||, and ! operators:

a b a && b a | | b !a
true true true true false
true false false true false
false true false true true
false false false false true
  • Logical operators can be used with booleans or with expressions that evaluate to booleans
boolean a = true && (!false || (true && false)); // a is true
boolean b = (7 <= 3) || (3 >= 5); // b is false
Intermediate Java

Let's practice!

Intermediate Java

Preparing Video For Download...