Skip to content

Module 2 · Java Basics — topic 2 of 5

Operators

Arithmetic, increment, compound assignment, relational, logical with short-circuiting, bitwise and the ternary operator, plus precedence rules.

Beginner 15 min read·Lesson 5 of 39 in Java Programming

Learning objectives

  • Use arithmetic, relational, logical and bitwise operators correctly
  • Predict the result of integer division, remainder and increment expressions
  • Use short-circuit evaluation to write safe conditions

Definition

Operators combine values (operands) into expressions. Java's operators are evaluated according to fixed precedence and associativity rules, and operands are evaluated strictly from left to right.

Introduction

Operators are the verbs of expressions: add these, compare those, combine these conditions. Most behave exactly as in C, but Java removes several of C's traps: the order in which operands are evaluated is defined (left to right), and conditions must be genuine boolean values.

Why it matters

Integer division and remainder appear in almost every program — splitting minutes into hours, checking even numbers, wrapping around an array.

Short-circuit operators let you write s != null && s.isEmpty() without risking a NullPointerException.

Detailed explanation

Arithmetic: + - * / %. When both operands are integers, / truncates toward zero (7 / 2 is 3, -7 / 2 is −3) and % gives a remainder with the sign of the left operand (-7 % 3 is −1). If either operand is a floating-point number, the division is floating point (7 / 2.0 is 3.5).

Increment and decrement: ++x changes x and then yields the new value; x++ yields the old value and then changes x. Use them as standalone statements to avoid confusion.

Compound assignment: x += 5 means x = (type of x)(x + 5) — note the hidden cast, which is why byte b = 10; b += 5; compiles but b = b + 5; does not.

Relational and equality: < <= > >= == != produce boolean. For objects, == compares references (is it the same object?), not contents — use .equals() for strings.

Logical: && (and), || (or) and ! (not) work on booleans. && and || *short-circuit*: the right side is evaluated only if needed. & and | on booleans always evaluate both sides.

Bitwise and shifts: & | ^ ~ on integers, << (left shift), >> (arithmetic right shift, keeps the sign) and >>> (logical right shift, fills with zeros).

Ternary: condition ? a : b chooses one of two values. Precedence, from high to low: unary (! ++ --), multiplicative, additive, shifts, relational, equality, bitwise, &&, ||, ternary, assignment. When in doubt, add parentheses.

Syntax

Java
int q = a / b, r = a % b; // quotient and remainder
x += 3; x *= 2; // compound assignment
boolean ok = age >= 18 && hasId; // short-circuit AND
String label = score >= 40 ? "pass" : "fail";
int flags = READ | WRITE; // bitwise OR
int half = n >> 1; // shift right
  • == on objects compares references; use equals for content.
  • Integer division by zero throws ArithmeticException.
  • Operands are always evaluated left to right.

Code examples

Division, remainder and increments

Java
public class Ops {
public static void main(String[] args) {
System.out.println(7 / 2 + " " + 7 % 2 + " " + 7 / 2.0);
System.out.println(-7 / 2 + " " + -7 % 3);
int x = 5;
int a = x++; // a = 5, x = 6
int b = ++x; // x = 7, b = 7
System.out.println(a + " " + b + " " + x);
int total = 10;
total += 5;
total *= 2;
System.out.println(total);
}
}
Output
3 1 3.5
-3 -1
5 7 7
30

Short-circuiting keeps you safe

Java
public class Safe {
public static void main(String[] args) {
String name = null;
if (name != null && name.length() > 3) {
System.out.println("long name");
} else {
System.out.println("no name or short name");
}
int age = 20;
String category = age < 13 ? "child" : age < 20 ? "teen" : "adult";
System.out.println(category);
}
}
Output
no name or short name
adult

Because name != null is false, name.length() is never evaluated.

More examples

Time conversion and bit flags

Java
public class Practical {
static final int READ = 1, WRITE = 2, EXECUTE = 4;
public static void main(String[] args) {
int seconds = 9_875;
int h = seconds / 3600, m = seconds % 3600 / 60, s = seconds % 60;
System.out.printf("%d s = %dh %02dm %02ds%n", seconds, h, m, s);
int perms = READ | WRITE;
System.out.println("can write: " + ((perms & WRITE) != 0));
System.out.println("can execute: " + ((perms & EXECUTE) != 0));
perms ^= WRITE; // toggle WRITE off
System.out.println("perms now: " + perms);
int n = 13;
System.out.println(n + " is " + (n % 2 == 0 ? "even" : "odd") + ", n << 2 = " + (n << 2) + ", -16 >> 2 = " + (-16 >> 2) + ", -16 >>> 28 = " + (-16 >>> 28));
}
}
Output
9875 s = 2h 44m 35s
can write: true
can execute: false
perms now: 1
13 is odd, n << 2 = 52, -16 >> 2 = -4, -16 >>> 28 = 15

Step-by-step explanation

  • seconds / 3600 gives whole hours (2); seconds % 3600 / 60 takes the leftover seconds and converts them to minutes (44); seconds % 60 gives the remaining seconds (35).
  • %02d pads a number to two digits with a leading zero.
  • Each permission is a different bit, so READ | WRITE is 3 and perms & WRITE is non-zero exactly when WRITE is set.
  • ^= toggles a bit: removing WRITE leaves only READ, which is 1.
  • n << 2 multiplies by 4; -16 >> 2 keeps the sign (−4); -16 >>> 28 shifts in zeros, leaving the top four bits, which are all ones (15).

Expected output

Running “Time conversion and bit flags” prints exactly:

TextOutput
9875 s = 2h 44m 35s
can write: true
can execute: false
perms now: 1
13 is odd, n << 2 = 52, -16 >> 2 = -4, -16 >>> 28 = 15

Practical applications

  • Converting seconds into hours, minutes and seconds for a timer
  • Checking even/odd and cycling through array indexes with %
  • Permission and option flags stored as bits
  • Ternary expressions for short display labels

Best practices

  • Use parentheses to make precedence obvious to readers.
  • Prefer && and || over & and | for conditions.
  • Don't modify the same variable twice in one expression, even though Java defines the order.

Common mistakes

Comparing strings with ==

Avoid

if (input == "yes") ...

Prefer

if (input.equals("yes")) ...

== checks whether both variables refer to the same object; two equal strings read at run time are usually different objects.

Expecting a decimal from integer division

Avoid

double avg = total / count; // 7 / 2 gives 3.0

Prefer

double avg = (double) total / count; // 3.5

The division happens in int before the result is converted to double; cast one operand first.

Important notes

  • Math.floorMod(-7, 3) returns 2, a remainder that is never negative — handy for wrapping indexes.
  • Java has no operator overloading for your own classes, except + for string concatenation.

Key takeaways

  • Integer / truncates toward zero and % keeps the sign of the left operand.
  • && and || short-circuit; use them to guard against null.
  • Use equals, not ==, to compare string contents.

Try it yourself

  1. 1
    Read a number of days and print it as weeks and days using / and %.
  2. 2
    Write a condition that is true for leap years using && and ||.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic