Operators are how you actually do things in Java โ calculations, comparisons, and decisions. Think of them as the verbs in your programming language. Without operators, all you have is data sitting there doing nothing.
Arithmetic Operators
You already know these from math class. Java uses the same symbols for basic math.
public class Main {
public static void main(String[] args) {
int a = 15;
int b = 4;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
}
}
One operator you might not have seen before is % โ the modulus operator.
It gives you the remainder of a division. 15 % 4 is 3
because 15 divided by 4 is 3 with 3 left over. Super useful for checking if a number
is even or odd.
Assignment Operators
You already know = for assigning values. But Java has shortcuts that
combine assignment with arithmetic.
public class Main {
public static void main(String[] args) {
int score = 10;
score += 5;
System.out.println(score);
score *= 2;
System.out.println(score);
}
}
score += 5 is the same as score = score + 5. Same for
-=, *=, /=, and %=. Less typing,
cleaner code.
Comparison Operators
These let you compare values. The result is always a boolean โ true
or false.
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 20;
System.out.println(x == y);
System.out.println(x != y);
System.out.println(x < y);
System.out.println(x > y);
}
}
A common mistake beginners make is using = instead of ==
for comparison. Remember: = assigns, == compares. Mix them
up and Java will let you know.
Logical Operators
Combine multiple conditions with logical operators. These are your decision-making tools.
public class Main {
public static void main(String[] args) {
int age = 20;
boolean hasID = true;
System.out.println(age >= 18 && hasID);
System.out.println(age < 16 || hasID);
System.out.println(!hasID);
}
}
&& means AND โ both conditions must be true. || means
OR โ at least one must be true. ! means NOT โ it flips true to false
and false to true. You will use these constantly when writing if statements and loops.