CodeBlanks Logo Icon CodeBlanks

Logical

Learn boolean logic with &&, ||, !.

Logical operators

Logical operators combine boolean values: && (and), || (or), ! (not).

boolean a = true;
boolean b = false;
System.out.println(a && b); // false
System.out.println(a || b); // true
System.out.println(!a);     // false

&& returns true only if both sides are true. || returns true if at least one side is true. ! flips the value.

&& and || short-circuit: if the left side already decides the result, the right side is not evaluated. This prevents possible errors.

Short-circuit behavior

The && and || operators short-circuit. If the left side already decides the result, the right side is not evaluated.

if (b != 0 && a / b > 1) { ... }

Here, if b == 0, && makes the left side false and the right side (a / b) is not evaluated. This avoids a division by zero.

The bitwise & and | do not short-circuit; they evaluate both sides. For logic, && and || are preferred.

Practice Print with logical operators

Write a Main class with a main method. Assign 20 to int age. Print age >= 18 && age <= 65 with println.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int age = 20;
        System.out.println(age >= 18 && age <= 65);
    }
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the logical and operator

Question
boolean result = true ____ false;
Answer
boolean result = true && false;

Explanation: The and operator is &&.

2 Match the logical operators

Term Meaning
&& And
|| Or
! Not
true True

3 What is the result of true || false?

  • false
  • true Correct answer
  • 1
  • 0

Explanation: || returns true if at least one side is true.

All lessons in Beginner