If variables are the nouns of programming, then Operators are the verbs. They are the special symbols that tell Java to perform specific mathematical, relational, or logical operations.
Think of a calculator. When you press +, you are using an operator. In Java, we use them for everything from calculating a discount on a price to checking if a user’s password is correct.
The 4 Main Types of Operators
1. Arithmetic Operators (The Math Teachers)
These are used to perform basic mathematical calculations.
+(Addition): Adds two values.-(Subtraction): Subtracts one from another.*(Multiplication): Multiplies two values./(Division): Divides one value by another.%(Modulus): This one is cool! It gives you the remainder of a division (e.g., 10÷3 is 3 with a remainder of 1).
2. Relational Operators (The Comparators)
These compare two values and always result in a boolean (true or false).
==(Equal to): Checks if two things are exactly the same.!=(Not equal to): Checks if two things are different.>and<(Greater than / Less than).>=and<=(Greater than or equal to / Less than or equal to).
3. Logical Operators (The Decision Makers)
These allow you to combine multiple comparisons.
&&(AND): Returns true only if both sides are true.||(OR): Returns true if at least one side is true.!(NOT): Reverses the result (turns true to false).
4. Assignment & Increment Operators (The Shortcuts)
=: Simple assignment.++: Increases a number by exactly 1 (e.g.,lives++in a game).--: Decreases a number by exactly 1.
The Code Example
public class OperatorsDemo {
public static void main(String[] args) {
// --- Arithmetic ---
int apples = 10;
int oranges = 5;
int totalFruit = apples + oranges; // 15
int difference = apples - oranges; // 5
// Modulus example (Checking if a number is even or odd)
int remainder = 10 % 3; // 10 divided by 3 is 3, remainder 1
// --- Relational & Logical ---
int myAge = 20;
int drinkingAge = 21;
boolean hasID = true;
// Can I enter the club? (Must be 21 AND have an ID)
boolean canEnter = (myAge >= drinkingAge) && hasID;
// --- Increment ---
int level = 1;
level++; // Now level is 2
// Printing the results
System.out.println("Total Fruit: " + totalFruit);
System.out.println("Remainder of 10/3: " + remainder);
System.out.println("Can I enter the club? " + canEnter);
System.out.println("Current Game Level: " + level);
}
}Expected Output:
Total Fruit: 15
Remainder of 10/3: 1
Can I enter the club? false
Current Game Level: 2