Skip to content

Logical Operators

  • Lesson
  • 2 min read
  • 4 of 5 in this chapter

Logical Operators

Sometimes, we want to check if several things are all true or if a few things are true.

For this reason, we have logical operators.

AND

If we want all the conditions to be true, we use AND. AND in code is represented by &&.

If we use &&, both of the options need true for the entire expression to be true..`

OR

If we want a few of the conditions to be true, we use OR. OR in code is represented by ||.

If we use ||, only one of the options needs to be true for the entire expression to be true.

Here's an example of AND and OR

Java
int x = 1;
int y = 2;
int z = 3;

boolean expOne = x == 1 && y > 3;
boolean expTwo = z > 3 || y < 3;
boolean expthree = (y => 2 && x < -1) || z == 3;

System.out.println(expOne);
System.out.println(expTwo);
System.out.println(expThree);

Can you guess what prints out?

Text
false
true
true

We can also use this with conditionals:

Java
int age = 13;

if(age >= 13 && age < 18) {
System.out.println("You are a teenager!");
}

int number = 8;

if(number > 10 || number < 9) {
System.out.println("This number works!");
}

number is obviously not greater than 10, but it is less than 9. OR only needs one of the conditions to be true to work.

Not

And sometimes, you may want to check if something is not equal to something else. And for that, we can use !.

! can invert a value from true to false, along with checking if something isn't equal to another thing.

Java
boolean result = true;
System.out.println(4 != 3);
System.out.println(!result);

This prints:

Text
true
false