Introduction to Java · Introduction to Java Programming

Logical Operators

Watch lectures

Logical Operators

1. What They Do (beginner)

Combine true/false answers: AND (&&), OR (||), NOT (!). Result is boolean. Used for ranges like "marks between 40 and 100".

2. Truth Table (memorize with example)

boolean pass = marks >= 40 && marks <= 100; // both must hold
boolean prize = rank == 1 || rank == 2;     // either holds
boolean fail = !(marks >= 40);              // opposite
A B A && B A || B !A
true true true true false
true false false true false
false false false false true

3. Short-Circuit Superpower (exam favourite!)

int x = 5, y = 0;
// && stops early: if left is false, right never runs (safe divide!)
if (y != 0 && x / y > 2) System.out.println("big"); // safe: x/y not evaluated!
// || stops early: if left true, right skipped
if (x == 5 || y++ > 0) {} // y++ NEVER runs (left true) → y stays 0!
System.out.println(y); // 0 — proves short-circuit

Use &&/|| (short-circuit). Single &/| always evaluate both (rare, see Boolean/Bitwise topics).

4. Traps

  • & vs &&: & runs both sides (side effects happen!), && may skip.
  • Range needs two compares: 40 <= marks && marks <= 100 (not 40 <= marks <= 100 like maths!).

5. Exam Points

  • Truth table + range program — 5 marks, very frequent.
  • Short-circuit trace (y++ skipped?) — 5 marks, favourite output Q.
Budget AppAndroid App

Pocketly on Android

Log daily food, travel, and hostel expenses instantly. Set monthly spending limits and see where your money goes without complex spreadsheets.

← All Introduction to Java Programming modules