Java · Basics

Operators

Operators let you calculate, compare and combine values.

Beginner 5 min Lesson 4 of 31Examples target Java 21 LTS (they also run on Java 25).
Before you start:Variables and Data Types
0/31 in Java
On this page · 5 min · Beginner

In simple words#

Operators are calculator buttons: + − × ÷ for maths, comparison buttons that answer yes/no, and logic buttons (and, or, not) that combine yes/no answers.

%
Remainder after division.
&& / ||
And / or, with short-circuit evaluation.
?:
Ternary: condition ? valueIfTrue : valueIfFalse.

Learning objectives#

  • Use arithmetic operators
  • Understand integer division
  • Combine conditions with logical operators
  • Use the ternary operator

Explanation#

Arithmetic: + - * / %. Dividing two ints gives an int (7 / 2 = 3).

Comparison: == != > < >= <= produce booleans. Compare objects (like Strings) with equals(), not ==.

Logical: && (and), || (or), ! (not). && and || short-circuit — the right side runs only if needed.

Assignment shortcuts (+=, -=), increment (++, --) and the ternary operator condition ? a : b.

Code example: Operators in a discount calculator#

JavaOperators in a discount calculator Illustrative
int total = 2499;
int items = 4;


System.out.println(total / items);        // 624   (integer division)
System.out.println(total % items);        // 3     (remainder)
System.out.println((double) total / items); // 624.75


boolean isMember = true;
boolean bigOrder = total >= 2000;
boolean freeDelivery = isMember || bigOrder;
String label = freeDelivery ? "Free delivery" : "₹49 delivery";


int points = 10;
points += 5;      // 15
points++;         // 16
System.out.println(label + ", points = " + points);
Expected output
624
3
624.75
Free delivery, points = 16

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. int / int drops the decimals.
  2. Casting one operand to double keeps them.
  3. || is true if either side is true.
  4. The ternary picks a label in one line.

Real-world use case#

Shopping carts use these operators for totals, discounts, free-delivery rules and loyalty points.

Common mistakes#

Unexpected integer division

5 / 2 is 2. Make one operand a double: 5 / 2.0.

Using = instead of ==

= assigns; == compares.

Best practices#

  • Use parentheses for clarity
  • Cast before dividing when decimals matter
  • Keep ternaries short
  • Compare strings with equals()

Remember this#

int / int = int.

% gives the remainder.

&& and || short-circuit.

Practice exercise#

Your task: Check whether a number n is even using %.

Show solution
Java Illustrative
boolean isEven = n % 2 == 0;

Mini quiz#

Operators quizMultiple choice Question 1 of 1

What is 17 % 5?

Score so far: 0/0

Want more? Practise all Java MCQs · Java interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.