Java Tutorial
🔍

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.

OperatorNameExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 742
/Division10 / 33 (integer division)
%Modulus (remainder)10 % 31
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 ÷ 3

Integer 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.

OperatorMeaningExampleEquivalent To
=Assignx = 5x = 5
+=Add and assignx += 3x = x + 3
-=Subtract and assignx -= 2x = x - 2
*=Multiply and assignx *= 4x = x * 4
/=Divide and assignx /= 2x = x / 2
%=Modulus and assignx %= 3x = 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); // 2

These 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.

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than7 > 4true
<Less than3 < 8true
>=Greater than or equal5 >= 5true
<=Less than or equal4 <= 3false
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); // true

Comparison 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 = 5 puts 5 into x
  • ›== compares two values: x == 5 asks "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 correct

4. Logical Operators

Logical operators combine multiple conditions into one. They always return a boolean.

OperatorNameMeaningExample
&&ANDBoth conditions must be trueage > 18 && hasId
||ORAt least one condition must be trueisAdmin || isOwner
!NOTReverses the boolean value!isLoggedIn
LOGICAL OPERATORS — TRUTH TABLE && (AND) Both must be true true && true = true true && false = false false && true = false false && false = false || (OR) At least one must be true true || true = true true || false = true false || true = true false || false = false ! (NOT) Flips the value !true = false !false = true
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 evaluated

This 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 runs

5. Unary Operators

Unary operators work on a single operand — no second value needed.

OperatorNameExampleResult
+Unary plus+55 (no change)
-Unary minus-5Negates the value
++Incrementx++ or ++xAdds 1 to x
--Decrementx-- or --xSubtracts 1 from x
!Logical NOT!truefalse

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 count

The 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); // Adult

This 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.

OPERATOR PRECEDENCE (HIGH → LOW) 1 ( ) Parentheses 2 ++ -- ! (unary) 3 * / % (multiplication, division, modulus) 4 + - (addition, subtraction) 5 < > <= >= (comparison) 6 == != (equality) 7+ && || ?: = (logical, ternary, assignment)
// 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 5

2. Integer division losing the decimal

double avg = 7 / 2; // ❌ 3.0 — integer division first double avg = (double) 7 / 2; // ✅ 3.5

3. Comparing Strings with ==

String s = "hello"; if (s == "hello") { } // ❌ unreliable if (s.equals("hello")) { } // ✅ always correct

4. 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

CategoryOperators
Arithmetic+ - * / %
Assignment= += -= *= /= %=
Comparison== != > < >= <=
Logical&& || !
Unary+ - ++ -- !
Ternary? :

The 3 Things to Remember From This Page

  1. ›Integer division drops the decimal — 7 / 2 = 3, not 3.5. Cast one operand to double to get the decimal: (double) 7 / 2 = 3.5
  2. ›= assigns, == compares — using = inside an if condition is one of the most common bugs in all of programming. Never compare with =.
  3. ›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 return boolean
  • ›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.

Show all 23 practice programs ↓
Basics & I/Ointermediate
Check Operator Precedence

Evaluates a mixed expression step by step to show the order Java applies different operator types in.

Basics & I/Obeginner
Demonstrate Bitwise OR

Applies the bitwise OR operator to two integers and shows the result at the bit level.

Basics & I/Obeginner
Demonstrate Bitwise XOR

Applies the bitwise XOR operator to two integers and shows the result at the bit level.

Basics & I/Obeginner
Demonstrate Bitwise NOT

Applies the bitwise NOT (complement) operator to an integer and explains why the result is negative.

Basics & I/Obeginner
Demonstrate Left Shift

Applies the left shift operator to an integer and shows how each shift doubles its value.

Basics & I/Obeginner
Demonstrate Right Shift

Applies the signed right shift operator to a negative integer and shows how the sign bit is preserved.

Basics & I/Ointermediate
Demonstrate Unsigned Right Shift

Applies the unsigned right shift operator to a negative integer and contrasts it with the signed right shift.

Basics & I/Ointermediate
Convert Seconds to Hours, Minutes and Seconds

Breaks a total second count down into whole hours, whole minutes, and leftover seconds.

Basics & I/Ointermediate
Convert Days to Years, Months and Days

Breaks a total day count down into whole years, whole months, and leftover days.

Basics & I/Obeginner
Calculate Area of Rectangle

Computes the area of a rectangle from its length and width.

Basics & I/Obeginner
Calculate Perimeter of Rectangle

Computes the perimeter of a rectangle from its length and width.

Basics & I/Obeginner
Calculate Area of Triangle

Computes the area of a triangle from its base and height.

Basics & I/Obeginner
Calculate Average of Numbers

Finds the average of a handful of individual numbers, without using an array or a loop.

Browse all Java programs →