Operators in Java

Site Admin · 11 Sep 2026 · 11 views

Operator Families

Arithmetic Operators

int a = 10, b = 3;
System.out.println(a + b);  // 13  addition
System.out.println(a - b);  // 7   subtraction
System.out.println(a * b);  // 30  multiplication
System.out.println(a / b);  // 3   integer division (drops fraction)
System.out.println(a % b);  // 1   remainder

Unary Operators

int n = 5;
int p = ++n;  // pre-increment: n becomes 6, p gets 6
int q = n++;  // post-increment: q gets 6, n becomes 7
boolean b = !true; // false

Relational and Logical Operators

int score = 85;
boolean passed = score >= 40 && score <= 100; // true
boolean special = (score == 100) || (score < 0);   // false
boolean isAdult = !(score < 18);                     // true

Note that && and || short-circuit: the second operand is only evaluated when needed.

Assignment and Compound Operators

int total = 0;
total += 10;   // same as total = total + 10
total -= 2;    // total = total - 2
total *= 3;    // total = total * 3
total /= 4;    // integer division
total %= 3;    // remainder

Ternary Operator

int age = 20;
String status = age >= 18 ? "adult" : "minor";
boolean isGrad = (age >= 18) ? true : false;

The ternary is a compact if-else: condition ? valueIfTrue : valueIfFalse.

Bitwise Operators

int x = 5;   // 0101
int y = 3;   // 0011
x & y        // 0001 = 1  (and)
x | y        // 0111 = 7  (or)
x ^ y        // 0110 = 6  (xor)
~x           // bitwise not
x << 2       // left shift: 5 * 4 = 20

Key Points

  • % gives the remainder of division.
  • && and || skip evaluation when the answer is already known.
  • Ternary ?: is a one-line if-else.
Share this post:

Comments (0)

Please login or register to comment.