← Back to Core Java Course | Chapter 3: Operators | Lesson 2 of 9

Java Arithmetic Operators

Addition and Subtraction

Addition and subtraction work exactly as expected across all of Java's numeric types (int, double, long, etc.), and Java automatically widens smaller types when needed during the calculation.

Example: Addition and Subtraction

java
public class Main {
	public static void main(String[] args) {
		int a = 5;
		double b = 2.5;
		System.out.println(a + b); // int widened to double automatically
		System.out.println(a - b);
	}
}

Multiplication and Division

Integer division silently truncates toward zero and drops any remainder -- 7 / 2 evaluates to 3, not 3.5 -- so dividing two ints when you want a fractional result requires casting at least one operand to double first.

Example: Multiplication and Division

java
public class Main {
	public static void main(String[] args) {
		System.out.println(7 / 2);         // 3 - integer division truncates
		System.out.println(7 / (double) 2); // 3.5 - cast forces a fractional result
	}
}

Modulo Operator

The modulo operator returns what's left over after division, so x % 2 == 0 is the standard idiom for testing whether x is even, since any even number leaves a remainder of 0 when divided by 2.

Example: Modulo Operator

java
public class Main {
	public static void main(String[] args) {
		int x = 10;
		System.out.println(x % 2 == 0); // true - standard idiom for testing even numbers
	}
}

Increment and Decrement

Prefix (++x) increments the variable and then evaluates to the new value; postfix (x++) evaluates to the old value first and increments afterward -- the difference only matters when the expression's result is used immediately, like in array[i++].

Example: Increment and Decrement

java
public class Main {
	public static void main(String[] args) {
		int x = 5;
		System.out.println(++x); // prefix: increments first, then evaluates - prints 6
		int y = 5;
		System.out.println(y++); // postfix: evaluates old value first - prints 5
	}
}

Compound Assignment

Compound operators like += fold the read, calculate, and write-back into one step -- total += price is shorthand for total = total + price, and beyond brevity it also avoids retyping the variable name and risking a typo.

Example: Compound Assignment

java
public class Main {
	public static void main(String[] args) {
		int total = 100;
		int price = 20;
		total += price; // shorthand for total = total + price
		System.out.println(total);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.