Java course menu
Java Operators: Arithmetic, Comparison, Logical, Assignment and Ternary
Learn Java operators: + - * / %, integer division, compound assignment, ++ and --, comparison and logical operators, short-circuit evaluation, the ternary operator, string concatenation with +, and operator precedence.
On this page
Operators are the symbols that calculate, compare and combine values. Most work like their maths equivalents; a few have behaviour every Java programmer must know.
Arithmetic operators#
public class Main {
public static void main(String[] args) {
System.out.println(7 / 2 + " " + 7.0 / 2);
System.out.println(7 % 2 + " " + 20 % 6 + " " + 7.5 % 2);
System.out.println(-7 / 2 + " " + -7 % 2);
}
}3 3.5
1 2 1.5
-3 -1- Integer division drops the fraction (towards zero).
- In Java,
%also works on decimals:7.5 % 2is1.5. - Integer division by zero throws an
ArithmeticException; dividing adoubleby zero givesInfinity(orNaNfor0.0 / 0).
Useful % patterns#
public class Main {
public static void main(String[] args) {
int n = 2026;
System.out.println(n % 2 == 0); // even?
System.out.println(n % 10); // last digit
System.out.println(n / 10); // remove the last digit
int totalMinutes = 135;
System.out.println(totalMinutes / 60 + "h " + totalMinutes % 60 + "m");
}
}true
6
202
2h 15mJava has no power operator; ^ is bitwise XOR. Use Math.pow(2, 10), which returns a double (1024.0).
Compound assignment#
public class Main {
public static void main(String[] args) {
int balance = 1000;
balance += 250; // 1250
balance -= 100; // 1150
balance *= 2; // 2300
balance /= 3; // 766 (integer division)
balance %= 7; // 3
System.out.println(balance);
}
}3Compound operators include an automatic cast: int x = 10; x *= 2.5; compiles and gives 25, while x = x * 2.5; does not compile.
Increment and decrement#
++ adds 1 and -- subtracts 1. Prefix (++i) changes the variable and then gives the new value; postfix (i++) gives the old value and then changes it:
public class Main {
public static void main(String[] args) {
int a = 5;
int b = ++a; // a = 6, b = 6
int c = 5;
int d = c++; // d = 5, c = 6
System.out.println(a + " " + b + " " + c + " " + d);
}
}6 6 6 5On a line of its own, i++; and ++i; do the same thing.
Comparison operators#
==, !=, <, >, <= and >= produce a boolean:
public class Main {
public static void main(String[] args) {
int age = 20;
System.out.println(age == 20);
System.out.println(age != 20);
System.out.println(age >= 18);
}
}true
false
trueFor objects such as String, == compares references, not contents. Use a.equals(b); see Strings.
Logical operators#
&& and || short-circuit: they stop as soon as the answer is known, which lets you guard a risky check:
public class Main {
public static void main(String[] args) {
int count = 0;
int total = 50;
if (count != 0 && total / count > 10) {
System.out.println("High average");
} else {
System.out.println("No data or low average");
}
}
}No data or low averageBecause count != 0 is false, total / count is never evaluated, so there is no ArithmeticException.
The ternary operator#
condition ? a : b chooses one of two values:
public class Main {
public static void main(String[] args) {
int marks = 72;
String result = marks >= 40 ? "pass" : "fail";
System.out.println(result);
}
}pass+ with strings#
If either operand of + is a String, + joins (concatenates) instead of adding. Evaluation goes left to right, which can surprise you:
public class Main {
public static void main(String[] args) {
System.out.println("Sum: " + 2 + 3);
System.out.println("Sum: " + (2 + 3));
System.out.println(2 + 3 + " is the sum");
}
}Sum: 23
Sum: 5
5 is the sumOperator precedence#
From highest to lowest (simplified):
- Postfix
i++,i-- - Unary
++i,--i,!,-, casts */%+-<><=>=instanceof==!=&&||? :=,+=,-=, …
When in doubt, use parentheses: they cost nothing and make intent clear.
Common mistakes#
Practice#
Practice exercise
Given int seconds = 4000;, print it as hours, minutes and seconds in the form 1h 6m 40s.
Show solution
public class Duration {
public static void main(String[] args) {
int seconds = 4000;
int hours = seconds / 3600;
int minutes = seconds % 3600 / 60;
int secs = seconds % 60;
System.out.println(hours + "h " + minutes + "m " + secs + "s");
}
}1h 6m 40sPractice exercise
Without running it, predict the output, then check:
int x = 10;
System.out.println(x++ + ++x);
System.out.println(x);Show solution
public class Predict {
public static void main(String[] args) {
int x = 10;
System.out.println(x++ + ++x);
System.out.println(x);
}
}22
12Java evaluates left to right: x++ gives 10 (then x becomes 11), ++x makes x 12 and gives 12, and 10 + 12 = 22. Unlike C++, this is well defined in Java, but it is still hard to read, so avoid writing it in real code.
Key takeaway#
Finished this lesson?