Mastering Operators in Java: Arithmetic, Logical & Relational

Mastering Operators in Java: Arithmetic, Logical & Relational

7 min read

1. Arithmetic operators

Operator

Meaning

Example

Result

+

Add

7 + 2

9

-

Subtract

7 - 2

5

*

Multiply

7 * 2

14

/

Divide

7 / 2

3 (not 3.5!)

%

Remainder (modulus)

7 % 2

1

Integer division: the number-one surprise

When both sides of / are whole numbers, Java does integer division and throws away the decimal part:

Java
public class Main {    public static void main(String[] args) {        System.out.println(7 / 2);      // 3        System.out.println(7.0 / 2);    // 3.5        System.out.println(7 / 2.0);    // 3.5        System.out.println(1 / 3);      // 0        int total = 250, count = 3;        double avg = total / count;     // 83.0 (division happened in int first!)        System.out.println(avg);    }}

The remainder operator %

% gives what is left over after division. It is surprisingly useful:

  • n % 2 == 0 means n is even.

  • n % 10 gives the last digit of n (1234 % 10 is 4).

  • n / 10 removes the last digit (1234 / 10 is 123).

  • minutes % 60 gives leftover minutes after taking out full hours.

These two tricks (% 10 and / 10) are the key to many problems in Session 10.

Dividing by zero

  • 10 / 0 with ints crashes the program with ArithmeticException: / by zero.

  • 10.0 / 0 with doubles gives Infinity (no crash).

2. Assignment and compound assignment

Java
int x = 10;x += 5;   // same as x = x + 5  → 15x -= 3;   // x = x - 3          → 12x *= 2;   // x = x * 2          → 24x /= 5;   // x = x / 5          → 4x %= 3;   // x = x % 3          → 1

3. Increment and decrement: ++ and --

x++ adds 1 to x. x-- subtracts 1. There are two forms, and the difference matters when the expression is used inside another expression:

  • Post-increment x++: use the current value first, then add 1.

  • Pre-increment ++x: add 1 first, then use the new value.

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

The classic interview puzzle. Dry-run it together on paper:

Java
int a = 5;int b = a++ + ++a;

Step

What happens

Value used

a after

1

a++: use 5, then a becomes 6

5

6

2

++a: a becomes 7, then use 7

7

7

3

b = 5 + 7

Result: a = 7, b = 12. In real code, never write expressions like this; they're for testing understanding only.

4. Relational (comparison) operators

These compare two values and always produce a boolean (true or false):

Operator

Meaning

Example

Result

==

equal to

5 == 5

true

!=

not equal to

5 != 3

true

> <

greater / less than

5 > 3

true

>= <=

greater / less than or equal

5 <= 5

true

Common mistakes

= assigns; == compares. if (x = 5) is a bug (in Java it's a compile error for ints, luckily). Say it aloud: "= is gets, == is equals."

5. Logical operators

Combine conditions:

Operator

Name

True when

&&

AND

both sides are true

||

OR

at least one side is true

!

NOT

flips true ↔ false

Java
public class Main {    public static void main(String[] args) {        int age = 20;        boolean hasId = true;        System.out.println(age >= 18 && hasId);   // true        System.out.println(age < 13 || age > 60); // false        System.out.println(!hasId);               // false    }}

Short-circuiting: && stops as soon as the left side is false (the answer can only be false). || stops as soon as the left side is true. This lets you write safe checks like count != 0 && total / count > 50, where the division never runs when count is 0.

How && short-circuits: the right side only runs if it can still change the answer.

6. + with text and numbers

Java evaluates + left to right. Once text is involved, everything after it becomes text joining:

Java
public class Main {    public static void main(String[] args) {        System.out.println("Sum: " + 5 + 3);    // Sum: 53        System.out.println("Sum: " + (5 + 3));  // Sum: 8        System.out.println(5 + 3 + " is sum");  // 8 is sum        System.out.println('A' + 1);            // 66  (char is a number underneath)    }}

7. Order of evaluation (precedence)

Just like BODMAS in school: *, /, % happen before + and -. Simplified order, from highest to lowest:

  1. Brackets ( )

  2. ++, --, !

  3. *, /, %

  4. +, -

  5. <, >, <=, >=

  6. ==, !=

  7. &&

  8. ||

  9. =, += and the other assignments

Professional rule: when in doubt, use brackets. (a + b) * c is clearer than relying on memory.

📝 Note: Bitwise operators

Java also has bitwise operators (&, |, ^, ~, <<, >>) that work on individual bits. They're rarely needed in everyday code. Mention that they exist and move on.

Interview questions

What is the output of System.out.println(10 / 4); and why?

2. Both operands are int, so Java performs integer division and discards the fractional part.

What is the difference between i++ and ++i?

Both increment i by 1. i++ evaluates to the old value; ++i evaluates to the new value. The difference only matters when the result is used within a larger expression.

What is short-circuit evaluation?

With && and ||, the right operand is evaluated only if needed. false && x never evaluates x; true || x never evaluates x.

Practice

  1. easy Given int totalSeconds = 3725;, print hours, minutes and seconds (answer: 1 h 2 m 5 s).

  2. easy Given a 3-digit number like 472, print its last digit, first digit and middle digit using only / and %.

  3. easy Calculate simple interest P * R * T / 100 for P = 50000, R = 7.5, T = 3.

  4. medium Swap two int variables using a third variable. Then do it without a third variable.

  5. medium Predict each output, then check:

Java
int x = 3;System.out.println(x++ * 2);System.out.println(x);System.out.println(--x + x++);System.out.println(x);
  1. medium Write a boolean expression that is true when year is a leap year: divisible by 4 and not by 100, or divisible by 400.

Problem 1
Java
int totalSeconds = 3725;int hours = totalSeconds / 3600;int minutes = (totalSeconds % 3600) / 60;int seconds = totalSeconds % 60;System.out.println(hours + " h " + minutes + " m " + seconds + " s");
Problem 2
Java
public class Digits {    public static void main(String[] args) {        int n = 472;        int last = n % 10;          // 472 % 10 = 2        int first = n / 100;        // 472 / 100 = 4 (integer division drops .72)        int middle = (n / 10) % 10; // 472 / 10 = 47, then 47 % 10 = 7        System.out.println("Last: " + last);        System.out.println("First: " + first);        System.out.println("Middle: " + middle);    }}

Output

Code
Last: 2First: 4Middle: 7

The two tools: % 10 picks the last digit, / 10 removes the last digit. Every digit problem in Session 10 is a combination of these two moves.

Problem 3
Java
public class SimpleInterest {    public static void main(String[] args) {        double p = 50000;        double r = 7.5;        int t = 3;        double si = p * r * t / 100;        System.out.println("Simple interest: " + si);        System.out.println("Total amount: " + (p + si));    }}

Output

Code
Simple interest: 11250.0Total amount: 61250.0

Because p and r are double, the whole calculation happens in decimals. If all three were int (and R were a whole number), P * R * T / 100 could lose the decimal part through integer division. Note the brackets in (p + si): without them, "Total amount: " + p + si would join the two numbers as text (Session 4, section 6).

Problem 4
Java
// With a temp variableint a = 5, b = 9;int temp = a;a = b;b = temp;// Without a temp variablea = a + b;   // a = 14b = a - b;   // b = 14 - 9 = 5a = a - b;   // a = 14 - 5 = 9
Problem 5

6 (uses 3, then x becomes 4), then 4, then 6 (--x makes x 3 and uses 3; x++ uses 3 and makes x 4; 3 + 3 = 6), then 4.

Problem 6
Java
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

© 2026 Rohit Parihar. All rights reserved.

RP

Discussion

?