Java Arithmetic Operators
In this page:
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: