Introduction to Java · Introduction to Java Programming

Arithmetic Operators

Watch lectures

Arithmetic Operators

1. The Five (+ shortcuts)

+ - * / % plus += -= *= /= %=. Beginners must master integer division and % (remainder) — they cause 80% mistakes.

2. Rules That Bite

Rule Example → Result Why
int/int = int (cut!) 7/2 → 3 (not 3.5!) both int → int
Need decimal? make one double 7/2.0 → 3.5 int+double → double
% = remainder 7%3 → 1, 10%5 → 0 (divisible!) great for even/odd, last digit
+ with String = join "5"+5 → "55" String wins
Precedence: * / % before + - 2+3*4 → 14 brackets to be safe: (2+3)*4 = 20

3. Code — Marks Average Done Right

public class Avg {
    public static void main(String[] args) {
        int a = 7, b = 2;
        System.out.println(a / b);     // 3 (trap! int division)
        System.out.println(a / 2.0);   // 3.5 (fix: .0 makes double)
        System.out.println(a % b);     // 1 (remainder)
        int n = 123;
        System.out.println(n % 10);    // 3 (last digit trick!)
        int x = 10;
        x += 5;  // x = x+5 → 15 (shortcut)
        System.out.println("Total:" + x + 5); // Total:155 (left-to-right join!)
        System.out.println("Total:" + (x + 5)); // Total:20 (brackets fix)
    }
}

4. Traps

  • 7/2 = 3 in Java (not 3.5) — #1 beginner bug in average programs.
  • "Total:"+x+5 joins left-to-right → brackets for math.
  • % with negatives: -7%3 = -1 (sign follows left).

5. Exam Points

  • Predict output (7/2, 7%3, "5"+5) — 5 marks, very frequent.
  • Average program with correct 2.0 — 3-5 marks, frequent.
Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.

← All Introduction to Java Programming modules