Java Operators
An operator is a symbol that performs an operation on one or more values.
+ adds two numbers. > compares them. && combines conditions. Operators are how your program does work — every calculation, every decision, every condition relies on them.
Java has six categories of operators. This page covers all of them with examples you can run immediately.
👉 What you'll learn here:
- ›Arithmetic operators — math operations
- ›Assignment operators — storing results efficiently
- ›Comparison operators — comparing values
- ›Logical operators — combining conditions
- ›Unary operators — single-value operations
- ›Ternary operator — one-line if/else
- ›Operator precedence — which runs first
🧘 You don't need to memorize every operator right now.
Read through once to understand what exists. You'll naturally remember the ones you use daily (+, -, *, /, ==, !=, &&, ||) within your first week of writing code.
1. Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 7 | 42 |
/ | Division | 10 / 3 | 3 (integer division) |
% | Modulus (remainder) | 10 % 3 | 1 |
int a = 10;
int b = 3;
System.out.println(a + b); // 13
System.out.println(a - b); // 7
System.out.println(a * b); // 30
System.out.println(a / b); // 3 ← integer division, decimal dropped
System.out.println(a % b); // 1 ← remainder of 10 ÷ 3Integer Division — The Most Common Gotcha
When both operands are int, division produces an int — the decimal part is silently dropped.
System.out.println(10 / 3); // 3 (not 3.333...)
System.out.println(7 / 2); // 3 (not 3.5)
System.out.println(1 / 4); // 0 (not 0.25)To get a decimal result, at least one operand must be a double:
System.out.println(10.0 / 3); // 3.3333333333333335
System.out.println((double) 10 / 3); // 3.3333333333333335
System.out.println(10 / 3.0); // 3.3333333333333335🔗 Full explanation of this with casting: → Type Casting →
The Modulus Operator %
% gives the remainder after division — not the quotient.
System.out.println(10 % 3); // 1 (10 = 3×3 + 1)
System.out.println(15 % 5); // 0 (15 = 5×3 + 0, divides evenly)
System.out.println(7 % 2); // 1 (7 = 2×3 + 1)Real-world uses of %:
// Check if a number is even or odd:
if (number % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
// Check if divisible by 5:
if (number % 5 == 0) {
System.out.println("Divisible by 5");
}
// Wrap around — e.g. clock hours (0 to 11):
int hour = (currentHour + 5) % 12;String Concatenation with +
When + is used with a String, it concatenates (joins) instead of adding:
String name = "Arjun";
int age = 22;
System.out.println("Name: " + name); // Name: Arjun
System.out.println("Age: " + age); // Age: 22
System.out.println("Sum: " + (10 + 20)); // Sum: 30
System.out.println("Sum: " + 10 + 20); // Sum: 1020 ← concatenation, not addition!⚠️ When a String appears on either side of +, everything becomes concatenation. Use parentheses to force addition first: "Sum: " + (10 + 20).
2. Assignment Operators
Assignment operators store a value into a variable. The basic one is =, but Java has shorthand versions that combine an operation with assignment.
| Operator | Meaning | Example | Equivalent To |
|---|---|---|---|
= | Assign | x = 5 | x = 5 |
+= | Add and assign | x += 3 | x = x + 3 |
-= | Subtract and assign | x -= 2 | x = x - 2 |
*= | Multiply and assign | x *= 4 | x = x * 4 |
/= | Divide and assign | x /= 2 | x = x / 2 |
%= | Modulus and assign | x %= 3 | x = x % 3 |
int x = 10;
x += 5;
System.out.println(x); // 15
x -= 3;
System.out.println(x); // 12
x *= 2;
System.out.println(x); // 24
x /= 4;
System.out.println(x); // 6
x %= 4;
System.out.println(x); // 2These shorthand operators are used constantly — especially += and -= in loops and counters.
3. Comparison Operators
Comparison operators compare two values and always return a boolean result — either true or false.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
> | Greater than | 7 > 4 | true |
< | Less than | 3 < 8 | true |
>= | Greater than or equal | 5 >= 5 | true |
<= | Less than or equal | 4 <= 3 | false |
int a = 10;
int b = 20;
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // false
System.out.println(a < b); // true
System.out.println(a >= 10); // true
System.out.println(b <= 20); // trueComparison operators are the backbone of if statements and loops:
int score = 75;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 75) {
System.out.println("Grade: B"); // ← this prints
} else {
System.out.println("Grade: C");
}⚠️ == vs = — the most common beginner mistake:
- ›
=assigns a value:x = 5puts 5 into x - ›
==compares two values:x == 5asks "is x equal to 5?"
Using = inside an if condition is a logic error — and one of the most common mistakes in all of programming.
⚠️ Never use == to compare Strings. Use .equals() instead:
String name = "Arjun";
name == "Arjun" // ❌ may give wrong result
name.equals("Arjun") // ✅ always correct4. Logical Operators
Logical operators combine multiple conditions into one. They always return a boolean.
| Operator | Name | Meaning | Example |
|---|---|---|---|
&& | AND | Both conditions must be true | age > 18 && hasId |
|| | OR | At least one condition must be true | isAdmin || isOwner |
! | NOT | Reverses the boolean value | !isLoggedIn |
int age = 20;
boolean hasId = true;
// AND — both conditions must be true
if (age >= 18 && hasId) {
System.out.println("Entry allowed"); // ✅ prints — both true
}
// OR — at least one must be true
boolean isWeekend = false;
boolean isHoliday = true;
if (isWeekend || isHoliday) {
System.out.println("Day off!"); // ✅ prints — isHoliday is true
}
// NOT — reverses a condition
boolean isLoggedIn = false;
if (!isLoggedIn) {
System.out.println("Please log in"); // ✅ prints — !false = true
}Short-Circuit Evaluation
&& and || use short-circuit evaluation — they stop evaluating as soon as the result is determined.
// && stops at the first false — no need to check the rest
false && someExpression // someExpression is NEVER evaluated
// || stops at the first true — no need to check the rest
true || someExpression // someExpression is NEVER evaluatedThis matters in practice:
String name = null;
// Safe — short-circuit prevents NullPointerException:
if (name != null && name.equals("Arjun")) {
System.out.println("Hello Arjun");
}
// If name is null, 'name != null' is false → && stops → name.equals() never runs5. Unary Operators
Unary operators work on a single operand — no second value needed.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Unary plus | +5 | 5 (no change) |
- | Unary minus | -5 | Negates the value |
++ | Increment | x++ or ++x | Adds 1 to x |
-- | Decrement | x-- or --x | Subtracts 1 from x |
! | Logical NOT | !true | false |
Increment and Decrement — Pre vs Post
++ and -- come in two flavors — and the difference matters when used in expressions:
int x = 5;
// Post-increment: use THEN increment
int a = x++;
System.out.println(a); // 5 ← original value used
System.out.println(x); // 6 ← x is now 6
// Pre-increment: increment THEN use
int y = 5;
int b = ++y;
System.out.println(b); // 6 ← incremented value used
System.out.println(y); // 6 ← y is now 6💡 In simple statements, pre and post make no difference:
count++; // same as
++count; // both just add 1 to countThe difference only matters when ++ or -- is used inside a larger expression like a = x++.
6. Ternary Operator
The ternary operator is a compact one-line if/else. It takes three operands — hence "ternary."
Syntax:
variable = (condition) ? valueIfTrue : valueIfFalse;int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status); // AdultThis is exactly equivalent to:
String status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}More examples:
int a = 15, b = 20;
int max = (a > b) ? a : b;
System.out.println("Max: " + max); // Max: 20
int score = 72;
String grade = (score >= 90) ? "A" : (score >= 75) ? "B" : "C";
System.out.println(grade); // C💡 When to use ternary: Use it for simple assignments where both branches are a single value. Avoid it for complex logic — nested ternaries (? : ? :) are hard to read and should be replaced with if/else.
Operator Precedence
When multiple operators appear in one expression, Java follows a specific order — like BODMAS/PEMDAS in mathematics.
// Without precedence knowledge — surprising results:
int result = 2 + 3 * 4;
System.out.println(result); // 14, not 20
// Because: 3 * 4 = 12 first, then 2 + 12 = 14
// Use parentheses to control order:
int result = (2 + 3) * 4;
System.out.println(result); // 20 ✅
// Mixed example:
boolean check = 5 + 3 > 2 * 4 && 10 != 9;
// Step 1: 5+3=8, 2*4=8 (arithmetic first)
// Step 2: 8>8 = false (comparison)
// Step 3: 10!=9 = true (comparison)
// Step 4: false && true = false (logical)
System.out.println(check); // false💡 Practical rule: When in doubt, use parentheses. They make intent clear and prevent precedence surprises. (a + b) * c is always clearer than relying on the reader to remember precedence rules.
A Complete Example — All Operators Together
public class OperatorsDemo {
public static void main(String[] args) {
// Arithmetic
int a = 17, b = 5;
System.out.println("17 + 5 = " + (a + b)); // 22
System.out.println("17 - 5 = " + (a - b)); // 12
System.out.println("17 * 5 = " + (a * b)); // 85
System.out.println("17 / 5 = " + (a / b)); // 3 (integer division)
System.out.println("17 % 5 = " + (a % b)); // 2 (remainder)
// Assignment shorthand
int x = 10;
x += 5; System.out.println("x after +=5: " + x); // 15
x *= 2; System.out.println("x after *=2: " + x); // 30
x -= 6; System.out.println("x after -=6: " + x); // 24
x /= 4; System.out.println("x after /=4: " + x); // 6
// Comparison
System.out.println("17 > 5: " + (a > b)); // true
System.out.println("17 == 5: " + (a == b)); // false
System.out.println("17 != 5: " + (a != b)); // true
// Logical
boolean big = a > 10; // true
boolean small = b < 3; // false
System.out.println("big && small: " + (big && small)); // false
System.out.println("big || small: " + (big || small)); // true
System.out.println("!big: " + (!big)); // false
// Increment
int count = 0;
count++;
count++;
count++;
System.out.println("count: " + count); // 3
// Ternary
String label = (a > b) ? "a is bigger" : "b is bigger";
System.out.println(label); // a is bigger
}
}Common Operator Mistakes
1. Using = instead of == in conditions
if (x = 5) { } // ❌ error — assigns 5 to x, not a comparison
if (x == 5) { } // ✅ compares x to 52. Integer division losing the decimal
double avg = 7 / 2; // ❌ 3.0 — integer division first
double avg = (double) 7 / 2; // ✅ 3.53. Comparing Strings with ==
String s = "hello";
if (s == "hello") { } // ❌ unreliable
if (s.equals("hello")) { } // ✅ always correct4. Confusing && with ||
// Age must be between 18 AND 60:
if (age >= 18 && age <= 60) { } // ✅ correct
// Wrong — can never be both < 18 AND > 60 at the same time:
if (age < 18 && age > 60) { } // ❌ always false — nothing satisfies this
if (age < 18 || age > 60) { } // ✅ correct for "outside range"5. Not using parentheses with mixed operators
boolean result = true || false && false;
// Reads as: true || (false && false) = true || false = true
// Precedence: && before ||. Add parentheses to make intent clear.Quick Reference — All Operators
| Category | Operators |
|---|---|
| Arithmetic | + - * / % |
| Assignment | = += -= *= /= %= |
| Comparison | == != > < >= <= |
| Logical | && || ! |
| Unary | + - ++ -- ! |
| Ternary | ? : |
The 3 Things to Remember From This Page
- ›Integer division drops the decimal —
7 / 2 = 3, not3.5. Cast one operand todoubleto get the decimal:(double) 7 / 2 = 3.5 - ›
=assigns,==compares — using=inside anifcondition is one of the most common bugs in all of programming. Never compare with=. - ›Use parentheses when mixing operators — don't rely on precedence rules in complex expressions. Parentheses make your intent explicit and your code readable.
Summary
- ›Arithmetic:
+-*/%— integer division truncates,%gives remainder - ›Assignment:
=and shorthands+=-=*=/=%= - ›Comparison:
==!=><>=<=— always returnboolean - ›Logical:
&&(both true),||(one true),!(flip) — use short-circuit evaluation - ›Unary:
++--increment/decrement — pre vs post matters inside expressions - ›Ternary:
condition ? valueIfTrue : valueIfFalse— compact one-line if/else - ›Precedence:
()→ unary →* / %→+ -→ comparison → equality →&& ||→?:→=
What to Read Next
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Applies each arithmetic operator — plus, minus, times, divide, and modulo — to the same two numbers.
Applies each relational operator to the same two numbers and prints the boolean result.
Applies the logical AND, OR, and NOT operators to two boolean values.
Applies the simple and compound assignment operators to the same variable, step by step.
Uses the ternary operator to pick the larger of two numbers in a single expression.
Applies the bitwise AND operator to two integers and shows the result at the bit level.
Computes body mass index from weight and height, then labels it with its category.
Reads two integers from the console and prints their sum.
Subtracts one fixed integer from another and prints the result.
Multiplies two fixed integers and prints the result.
Show all 23 practice programs ↓Show fewer ↑
Evaluates a mixed expression step by step to show the order Java applies different operator types in.
Applies the bitwise OR operator to two integers and shows the result at the bit level.
Applies the bitwise XOR operator to two integers and shows the result at the bit level.
Applies the bitwise NOT (complement) operator to an integer and explains why the result is negative.
Applies the left shift operator to an integer and shows how each shift doubles its value.
Applies the signed right shift operator to a negative integer and shows how the sign bit is preserved.
Applies the unsigned right shift operator to a negative integer and contrasts it with the signed right shift.
Breaks a total second count down into whole hours, whole minutes, and leftover seconds.
Breaks a total day count down into whole years, whole months, and leftover days.
Computes the area of a rectangle from its length and width.
Computes the perimeter of a rectangle from its length and width.
Computes the area of a triangle from its base and height.
Finds the average of a handful of individual numbers, without using an array or a loop.