Nanfeng

Notes on software development, code, and curious ideas

Operators in Java

Java operators act on one, two, or three operands and produce a result.

Arithmetic operators

1
2
3
4
5
6
7
8
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
System.out.println(a % b); // 1: remainder

Unary ++ and -- increment or decrement a variable. Prefix form changes it before yielding a value; postfix form yields the previous value first.

Assignment operators

= assigns a value. Compound forms combine an operation with assignment:

1
2
3
4
5
6
int total = 10;
total += 5; // 15
total *= 2; // 30
total -= 4; // 26
total /= 2; // 13
total %= 5; // 3

Comparison operators

==, !=, <, >, <=, and >= return a Boolean result.

1
2
boolean sameNumber = a == b;
boolean inRange = a >= 0 && a <= 100;

For objects, == compares references. Use .equals() when the class defines value equality:

1
boolean sameText = firstString.equals(secondString);

Logical operators

  • &&: logical AND with short-circuiting
  • ||: logical OR with short-circuiting
  • !: logical negation
1
boolean canEnter = hasTicket && !isBanned;

Bitwise and shift operators

Integral types support &, |, ^, and ~, plus <<, >>, and >>> shifts:

1
2
3
int flags = 0b0101;
boolean secondBitSet = (flags & 0b0010) != 0;
int doubled = 4 << 1; // 8

>> preserves the sign bit, while >>> shifts in zeros.

Conditional operator

The ternary operator selects one of two values:

1
String result = score >= 60 ? "Pass" : "Fail";

Parentheses are helpful when precedence is not immediately obvious. Prefer readable expressions over relying on memorized precedence rules.

+