This site is retired and is no longer updated since November 2021. Please visit our new website at https://www.teamscode.org for up-to-date information!
Logical Operators

Code Bar
&& AND
|| OR
! NOT

Logical operators are operators that form compound Boolean expressions that return a Boolean result. Essentially, the AND/OR operations are put in between two existing Boolean expressions and determine a new Boolean result.

The three main logical operators are shown above in the Code Bar. The meanings of these operations are:

  • && returns true if both Boolean expressions are true

  • || returns true if one of the Boolean expressions are true

  • ! is put in front of a Boolean to reverse its value

Truth tables are tables that represent the outcome of the operations. The truth tables for the AND/OR operations are:

      

These logical operators have a special syntax, which is shown below:

true && false 		-> false

false || true 		-> true

!false 			-> true

!true 			-> false

Logical operators are most commonly used in conjunction with relational operators, which were described last lesson (Relational Operators). Here is an example:

(4 == 5) || (7 >= 3)

Since (4 == 5) is false, and (7 >= 3) is true, this statement can be further broken down into the following:

false || true		-> true

Looking at the truth tables, we can see that the above expression evaluates to true. Here are some more examples:

(5 > 4) && (6 == 6) 	-> true

(3 <= 2) || (50 != 50) 	-> false

!(6 > 3) 		-> false

These operators are often used in if statements, for loops, and while loops, which we will get to in lessons 12-15, Loops and Conditionals.

Lesson Quiz

What is output to the console in each of the following scenarios?

	int i = 5;

	boolean x = (i > 5) && ((12 * 2) != 24);

	System.out.println(x);
a. True
b. False
	System.out.println(!((5000 / 10) > 700));
a. True
b. False
	double y = 3.65;

	System.out.println(((y * 5) < 15) || true);
a. True
b. False

Written by Chris Elliott

Notice any mistakes? Please email us at learn@teamscode.com so that we can fix any inaccuracies.