Skip to content

Beginner · Getting started with Java · topic 4 of 60 · 25 min

Operators and expressions

Explanation

Java has arithmetic (+ - * / %), assignment (= += -=), increment (++ --), comparison (== != < >) and logical (&& || !) operators. Dividing two ints gives an int (7 / 2 is 3). Ints silently overflow when they pass about 2.1 billion. && and || short-circuit, and brackets make precedence clear.

Arithmetic

java
System.out.println(7 + 2);    // 9
System.out.println(7 - 2);    // 5
System.out.println(7 * 2);    // 14
System.out.println(7 / 2);    // 3    (int / int → int, the decimal part is cut off)
System.out.println(7 % 2);    // 1    (remainder)
System.out.println(7.0 / 2);  // 3.5  (one double makes it a double division)
System.out.println(-7 / 2);   // -3   (truncates toward zero)
System.out.println(-7 % 2);   // -1   (the sign follows the left side)
Careful: Integer division is the most common Java arithmetic bug. average = (a + b) / 2 with ints loses the .5. Make one side a double: (a + b) / 2.0, or cast: (double) (a + b) / 2.

Assignment and compound operators

java
int stock = 50;
stock += 10;   // 60
stock -= 5;    // 55
stock *= 2;    // 110
stock /= 3;    // 36 (int division)
stock %= 10;   // 6

byte b = 10;
// b = b + 1;  // compile error: b + 1 is an int, cannot store in byte without a cast
b += 1;        // OK: compound operators include an automatic cast

Increment and decrement

java
int i = 5;
int a = i++;   // a = 5, then i becomes 6 (postfix: use, then add)
int b = ++i;   // i becomes 7, then b = 7 (prefix: add, then use)
System.out.println(a + " " + b + " " + i);   // 5 7 7

Comparison and logical operators

Comparisons (==, !=, <, <=, >, >=) give a boolean. && (and) and || (or) combine booleans and short-circuit: in a && b, if a is false, b is never evaluated. This is used for safety checks like name != null && name.length() > 0.

java
int age = 20;
boolean hasId = true;
System.out.println(age >= 18 && hasId);   // true
System.out.println(age < 13 || age > 60); // false
System.out.println(!hasId);               // false
Careful: For objects such as Strings, == compares whether two references point to the SAME object, not whether the text is equal. Compare String contents with .equals(...). Module 3 explains why "a" == "a" sometimes seems to work.

Overflow

An int has a fixed size, so going past its maximum wraps around to the most negative value without any error. This is called overflow. Use long for large values, or Math.addExact / Math.multiplyExact, which throw an ArithmeticException on overflow instead of silently wrapping.

java
int max = Integer.MAX_VALUE;            // 2147483647
System.out.println(max + 1);            // -2147483648 (overflow!)
long ok = (long) max + 1;               // 2147483648
// Math.addExact(max, 1);               // throws ArithmeticException: integer overflow

Precedence and Math

As in school: * / % before + -, comparisons after arithmetic, then &&, then ||. Use brackets when in doubt. The Math class gives Math.max, Math.min, Math.abs, Math.pow (returns double), Math.sqrt, Math.round (returns long for a double argument), Math.floor and Math.ceil.

Think of it like this: Integer division is like sharing 7 laddoos among 2 children without breaking any: each gets 3, and 1 is left over (that leftover is 7 % 2). If you want 3.5 each, you must allow breaking laddoos: use doubles.
Tip: Write conditions that read like English and name them: boolean eligibleForLoan = salary >= 25000 && creditScore >= 700;. Then the if statement explains itself.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Operators and expressions · 1/6

Operators

In this lesson you will calculate and compare with Java operators.

Prefer a video by a teacher? Find free videos on “java operators integer division increment overflow tutorial” on YouTube ↗

In real life: Splitting a bill and checking eligibility

A group-ordering app splits a ₹1,000 bill between 3 people and shows the remainder, then checks whether the order qualifies for free delivery. Note the integer division and % for the leftover rupee.

java
public class Split {
    public static void main(String[] args) {
        int bill = 1000, people = 3;
        int each = bill / people;        // 333
        int left = bill % people;        // 1
        boolean freeDelivery = bill >= 499 && people <= 4;
        System.out.println(each + " each, " + left + " left, free delivery: " + freeDelivery);
    }
}
Prints 333 each, 1 left, free delivery: true

Practice (0/3 done)

Task 1 · Question

What does this print? int x = 10; int y = x++ + ++x; System.out.println(x + " " + y);

Task 2 · Question

Which line does NOT compile? 1: short s = 5; 2: s += 3; 3: s = s + 3; 4: int t = s + 3;

Task 3 · Code · Javascript

The same integer-division idea in JavaScript, which runs here: JavaScript has no int type, so write javaIntDivide(a, b) that returns what Java's int division a / b would give (truncate toward zero), and javaRemainder(a, b) for Java's % (same sign as a).

Quick quiz

Question 1

1.What is 17 / 5 in Java with ints?

Question 2

2.What is 17 % 5?

Question 3

3.In a && b, when is b NOT evaluated?

Question 4

4.Integer.MAX_VALUE + 1 gives…

Read more (free)

Before this, learn

This topic builds on these. If something here feels new, open them first.

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What is 17 / 5 in Java with ints?

Answer: 3

Integer division drops the decimal part.

What is 17 % 5?

Answer: 2

5 × 3 = 15, remainder 2.

In a && b, when is b NOT evaluated?

Answer: When a is false

&& short-circuits: if a is false, the result is false regardless of b.

Integer.MAX_VALUE + 1 gives…

Answer: Integer.MIN_VALUE (-2147483648)

int overflow wraps around silently.

Which expression is undefined behaviour?Related

Answer: i = i++ + 1

i is modified twice without sequencing.

From Operators

int a = 7; int b = (a % 2 == 0) ? 1 : 0; What is b?Related

Answer: 0

7 % 2 is 1, so the condition is false and b gets 0.

From Operators and decisions: if, else and switch

What does Math.Round(2.5) return in C#?Related

Answer: 2

By default C# uses banker's rounding: halfway values go to the nearest even number.

From Operators, conversions and parsing input

Is it legal to compute a + n for int a[n]?Related

Answer: Yes, one past the end may be computed but not dereferenced

The one-past-the-end rule.

From Pointer arithmetic

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Getting started with Java” before its exam: Type conversion and reading input.
  2. Module 1 exam: Getting started with Java · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Control flow and methods. 60 topics left in the course before the final exam.

← Previous: Variables and primitive types