Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 02 / Topic 3 of 9

Operators

An operator works on values, like + (add) or >= (compare). Java's arithmetic, comparison and logical operators are close to Python's, but a few things differ.

int laddoos = 7;
int boxSize = 2;

System.out.println(laddoos / boxSize);            // int / int truncates towards zero
System.out.println(laddoos % boxSize);             // remainder
System.out.println((double) laddoos / boxSize);    // cast one side to get a real division

Output (examples/03_operators.java):

3
1
3.5
true
7
14
20
1024.0
true
false
1
7
6
-6
10
2
Group Operators Example → result
Arithmetic + - * / % 7 % 2 → 1
Comparison == != > < >= <= 5 != 3 → true
Logical && || ! !(5 > 3) → false
Assignment = += -= *= /= %= stock -= 3
Bitwise & | ^ ~ << >> 5 & 3 → 1

There is no ** operator in Java. Use Math.pow(base, exponent), which always returns a double:

System.out.println(Math.pow(2, 10));   // 1024.0

Precedence (high → low, the common ones): () → * / % → + - → < <= > >= → == != → && → ||.

System.out.println(2 + 3 * 4);     // 14, * before +
System.out.println((2 + 3) * 4);   // 20, brackets first

Logical operators use &&, ||, !, not Python's and, or, not. They short-circuit the same way: in a || b, b is never evaluated if a is already true.

Bitwise operators work on the binary bits of a whole number: & (AND), | (OR), ^ (XOR), ~ (NOT), <</>> (shift). You will rarely need these outside low-level or performance code, but they exist and behave as shown above.

Full program: examples/03_operators.java.

Done here? The practice set for Part 2 — including the solutions — is on the part page.

Search the guide