SyntaxPilot
Courses/Java/Lesson 3
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Java · Lesson 3 of 51

Operators

scheduled

These are the notes for Java episode 3. You will learn the arithmetic operators and why 250 / 4 gives 62 in Java, the modulus operator %, += and ++ (and the a++ vs ++a trap), the six comparison operators and the = vs == mistake, the logical operators &&, || and !, short-circuit evaluation that prevents a / by zero crash, and operator precedence. Every example below runs as-is in the SyntaxPilot compiler.

The problem: the missing 50 paise

Four friends go to a cafe. The bill is ₹250. On a calculator, 250 ÷ 4 = 62.50, so each pays ₹62.50. Now the same maths in Java:

public class Main {
    public static void main(String[] args) {
        int bill = 250;
        int friends = 4;
        System.out.println("Each pays: " + bill / friends);
    }
}

Output:

Each pays: 62

4 × 62 = 248. Who pays the other ₹2? There is no error: Java silently chopped off the decimal. No error, just wrong money.

Why: integer division

Java's rule: int / int = int. The decimal part is cut off, not rounded.

Expression Result Why
250 / 4 62 62.5 → decimal part cut off
7 / 2 3 3.5 → 3
99 / 100 0 0.99 → 0 (not rounded up to 1)
-7 / 2 -3 cut towards zero, not down to -4

The fix: make one side a decimal. Then the division is done in double:

public class Main {
    public static void main(String[] args) {
        System.out.println("Each pays: " + 250.0 / 4);
        double bill = 250;
        int friends = 4;
        System.out.println("Each pays: " + bill / friends);
    }
}

Output:

Each pays: 62.5
Each pays: 62.5

The 50 paise are back. When both values are int variables, you convert one with type casting, (double) bill / friends, which is the next episode.

The five arithmetic operators

public class Main {
    public static void main(String[] args) {
        int a = 17, b = 5;
        System.out.println(a + b);  // 22
        System.out.println(a - b);  // 12
        System.out.println(a * b);  // 85
        System.out.println(a / b);  // 3
        System.out.println(a % b);  // 2
    }
}

Output:

22
12
85
3
2
Operator Meaning 17 ? 5
+ add 22
- subtract 12
* multiply 85
/ divide (integer division for two ints) 3
% modulus: what is left over after division 2

% is not a percentage. Five goes into seventeen three times, with two left over.

% : what's left over

A sweet shop makes 125 samosas in the morning, and each box holds 12.

  • How many full boxes? 125 / 12 = 10. Here integer division is exactly what you want: you cannot sell half a box.
  • How many are left over? 125 % 12 = 5.
  • Even or odd? n % 2 is 0 for even, 1 for odd.
public class Main {
    public static void main(String[] args) {
        int samosas = 125;
        int perBox = 12;
        System.out.println("Full boxes: " + samosas / perBox);
        System.out.println("Left over: " + samosas % perBox);
        System.out.println("17 % 2 = " + 17 % 2);
    }
}

Output:

Full boxes: 10
Left over: 5
17 % 2 = 1

Integer division and modulus work as a pair: / gives the full groups, % gives the leftovers. Typical uses: minutes and seconds, even/odd checks, the last digit of a number (n % 10), wrapping around (day of the week).

Edge cases worth knowing:

  • The sign of % follows the left side: -7 % 2 is -1, so check odd numbers with n % 2 != 0, not n % 2 == 1.
  • % also works on decimals: 7.5 % 2 is 1.5.

+= and ++ : the gatekeeper's counter

A man at a fair's gate counts visitors. For each one: visitors = visitors + 1;. Written a thousand times, the name appears twice each time, and one typo (visitor instead of visitors) is a bug. A click counter is easier: one click, plus one.

public class Main {
    public static void main(String[] args) {
        int visitors = 0;
        visitors = visitors + 1;
        visitors += 1;
        visitors++;
        System.out.println("Visitors: " + visitors);
    }
}

Output:

Visitors: 3

All three lines do the same job: add 1.

Short form Means
x += 50 x = x + 50
x -= 3 x = x - 3
x *= 2 x = x * 2
x /= 4 x = x / 4
x %= 2 x = x % 2
x++ / ++x add 1
x-- / --x subtract 1

Hidden cast (interview point): compound operators cast the result back to the variable's type. int x = 10; x = x * 2.5; is a compile error (possible lossy conversion from double to int), but x *= 2.5; compiles and makes x equal to 25.

a++ vs ++a

public class Main {
    public static void main(String[] args) {
        int a = 5;
        int b = a++;
        System.out.println("a = " + a + ", b = " + b);
        int c = 5;
        int d = ++c;
        System.out.println("c = " + c + ", d = " + d);
    }
}

Output:

a = 6, b = 5
c = 6, d = 6
  • a++ (post-increment): use, then add. It hands over the old value (5) first, then increases a to 6.
  • ++c (pre-increment): add, then use. It increases c to 6 first, then hands over 6.

On a line of its own (visitors++;) there is no difference. It only matters when the value is used in the same expression.

Comparison operators

Some questions have a yes/no answer: a vegetable seller's scale (is it at least 1 kg?), a voter-ID counter (is the age 18 or more?), a ticket check (is it exactly seat 17?). In Java, a comparison always answers with a boolean: true or false.

Operator Question
== equal to?
!= not equal to?
> greater than?
< less than?
>= at least?
<= at most?
public class Main {
    public static void main(String[] args) {
        int age = 17;
        System.out.println(age >= 18);
        System.out.println(age == 17);
        System.out.println(age != 17);
    }
}

Output:

false
true
false

= puts, == asks

A single = puts a value in a box; a double == asks a question.

public class Main {
    public static void main(String[] args) {
        int age = 17;
        boolean adult = (age = 18);
    }
}
Main.java:4: error: incompatible types: int cannot be converted to boolean

age = 18 puts 18 into age, and the result is an int, not an answer. Fix: (age == 18). Java catches this mistake for ints; many languages (like C) do not.

One case Java cannot catch: when the variable itself is a boolean.

boolean isOpen = false;
if (isOpen = true) {
    System.out.println("Shop is open?!");
}
System.out.println(isOpen);

Output:

Shop is open?!
true

isOpen = true assigns true, so the condition is always true. For booleans, write if (isOpen) instead of comparing with == at all.

Logical operators: &&, || and !

One question is not always enough. At the cinema:

Operator Name Rule Example
&& AND both must be true entry: 18+ and has a ticket
|| OR at least one must be true discount: student or senior
! NOT flips the answer !hasTicket
public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean hasTicket = false;
        boolean isStudent = true;
        System.out.println("Can enter: " + (age >= 18 && hasTicket));
        System.out.println("Discount: " + (isStudent || age >= 60));
        System.out.println("No ticket: " + !hasTicket);
    }
}

Output:

Can enter: false
Discount: true
No ticket: true

No entry, because there is no ticket and AND needs both. Discount yes, because OR needs only one. Note the brackets around the conditions: without them, "Can enter: " + age >= 18 would try to compare a String with a number.

Truth table:

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

Short-circuit evaluation saves a crash

All your friends cancel: friends = 0. The program asks whether each share is more than ₹20:

public class Main {
    public static void main(String[] args) {
        int total = 100;
        int friends = 0;
        System.out.println(total / friends > 20);
    }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.main(Main.java:5)

This is not a compile error. The program started, then crashed while running: a runtime exception. Now put a safety check first, joined with &&:

public class Main {
    public static void main(String[] args) {
        int total = 100;
        int friends = 0;
        System.out.println(friends != 0 && total / friends > 20);
    }
}

Output:

false

No crash. The left side of && was false, so the answer was already known and Java never evaluated the right side. That is short-circuiting.

  • && stops when the left side is false.
  • || stops when the left side is true: friends == 0 || 100 / friends > 20 prints true without dividing.
  • The single & and | also work on booleans but do not short-circuit: friends == 0 | 100 / friends > 20 still crashes with / by zero.

Put the safety check first in &&.

Extra: dividing a double by zero does not crash. 10.0 / 0 prints Infinity and 0.0 / 0 prints NaN (not a number). Only integer division by zero throws ArithmeticException.

Operator precedence: who goes first?

A student scores 80 in maths and 90 in science. The average should be 85:

public class Main {
    public static void main(String[] args) {
        int maths = 80;
        int science = 90;
        System.out.println("Average: " + maths + science / 2);
        System.out.println("Average: " + (maths + science) / 2);
        System.out.println(2 + 3 * 4);
    }
}

Output:

Average: 8045
Average: 85
14
  • Line 1: / goes first (90 / 2 = 45), then the + trap from episode 1 glues 80 and 45 onto the text: 8045.
  • Line 2: brackets go first: (80 + 90) / 2 = 85.
  • Line 3: * before +, just like BODMAS: 2 + 12 = 14, not 20.
Order Operators
1 ( ) brackets
2 ++ -- !
3 * / %
4 + -
5 < > <= >=, then == !=
6 &&, then ||
7 = += -= … (last of all)
  • Same level? Left to right: 10 - 4 - 3 is 3, and 100 / 10 / 5 is 2.
  • Assignment is last, which is why the whole right side is calculated before it goes into the box.
  • You do not need to memorise it: when in doubt, add brackets. It also makes the code easier to read.

Common mistakes (and the real error messages)

Mistake Code What happens
int / int for money 250 / 4 no error, prints 62
= instead of == boolean adult = (age = 18); incompatible types: int cannot be converted to boolean
Dividing an int by zero total / friends with friends = 0 Exception in thread "main" java.lang.ArithmeticException: / by zero
Mixing text and maths without brackets "Average: " + maths + science / 2 no error, prints Average: 8045
Decimal result into an int x = x * 2.5; incompatible types: possible lossy conversion from double to int
= on a boolean variable if (isOpen = true) no error, always true
n % 2 == 1 for negative odd numbers -7 % 2 == 1 no error, false (because -7 % 2 is -1)

Mini project: bill splitter with a tip

A bill of ₹1250, four friends and a 10% tip:

public class Main {
    public static void main(String[] args) {
        int bill = 1250;
        int friends = 4;
        double tipPercent = 10;
        double tip = bill * tipPercent / 100;
        double total = bill + tip;
        double each = total / friends;
        System.out.println("Bill:\t" + bill);
        System.out.println("Tip:\t" + tip);
        System.out.println("Total:\t" + total);
        System.out.println("Each:\t" + each);
    }
}

Output:

Bill:   1250
Tip:    125.0
Total:  1375.0
Each:   343.75

tipPercent is a double, so bill * tipPercent / 100 is decimal maths, and total is a double, so dividing by friends keeps the paise. Not a single paisa missing. Try it with your last restaurant bill.

Practice

  1. Convert 125 seconds into minutes and seconds using / and %.
  2. Check whether a year number is even using %.
  3. Write canVote = age >= 18 && hasVoterId and print it.
  4. Predict the output of System.out.println(10 + 20 / 5 * 2 - 3 % 2);.
  5. Explain why int a = 5; System.out.println(a++ + ++a); prints 12.
Solutions and hints
  1. int seconds = 125; System.out.println(seconds / 60 + " min " + seconds % 60 + " sec"); prints 2 min 5 sec. (Here the maths comes before any text, so it is added, not glued.)
  2. int year = 2026; System.out.println("Even year: " + (year % 2 == 0)); prints Even year: true.
  3. int age = 19; boolean hasVoterId = true; boolean canVote = age >= 18 && hasVoterId; System.out.println("Can vote: " + canVote); prints Can vote: true.
  4. 17. 20 / 5 = 4, 4 * 2 = 8, 3 % 2 = 1, then left to right: 10 + 8 - 1 = 17.
  5. Left to right: a++ hands over 5 and makes a 6; then ++a makes a 7 and hands over 7. 5 + 7 = 12.

Quick quiz

What will this print?

int a = 5;
System.out.println(a++ + ++a);
  • A. 10
  • B. 11
  • C. 12
  • D. 13
Answer

C. 12. Left to right: a++ uses 5 (then a becomes 6), then ++a makes a 7 and uses 7. 5 + 7 = 12.

Interview questions

  • Why does 250 / 4 give 62 in Java, and how do you get 62.5?
  • What is the difference between a++ and ++a? What does int x = 10; x = x++; leave in x? (It stays 10: the old value is saved, x is incremented, then the old value is assigned back.)
  • What is the difference between = and ==?
  • What is short-circuit evaluation? What is the difference between && and &?
  • Why does x *= 2.5 compile when x = x * 2.5 does not (for an int x)?
  • What happens on integer division by zero vs double division by zero?
  • What is operator precedence? Give an example where brackets change the answer.

Summary

  • + - * / %: int / int cuts the decimal (250 / 4 = 62); make one side decimal to fix it.
  • % gives the leftover: boxes and samosas, even/odd, minutes and seconds.
  • +=, -=, ++, -- are shortcuts; a++ = use then add, ++a = add then use.
  • Comparisons give a boolean; = puts, == asks.
  • && needs both, || needs either, ! flips; && and || short-circuit, so put the safety check first.
  • Precedence: brackets, then * / %, then + -, then comparisons, then && ||, assignment last. When in doubt, add brackets.

Next episode: so far every value was typed into the code. Next we take input from the user with Scanner, and convert between int and double with type casting.