skip to content

Operators

Java's full operator set and the precedence and associativity rules that decide how an expression parses. Interviewers use operator questions for quick puzzles about integer division, short-circuiting and shifts.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

page 1 of 2

What are the arithmetic operators in Java and what does each one do?

level: juniorimportance: must knowfreq 70%

answer

  1. 5 binary: + - * / % ; 2 unary: + -
  2. overloaded = String concatenation
  3. numeric promotion -> result type = widest operand
  4. 5/2 == 3 (int), 5.0/2 == 2.5
  5. / % bind tighter than + -

basics

~10 s

Java has +, -, *, / and % for add, subtract, multiply, divide, and remainder. There are also unary + and - that keep or flip a number's sign.

solid answer

~40 s

Java's binary arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division) and % (remainder/modulo). The + is also overloaded for String concatenation, so when either side is a String the result is text. There are unary + and - operators: unary minus negates its operand, unary plus is essentially a no-op kept for symmetry. Operands first undergo numeric promotion (byte/short/char widen to int; if either side is long/float/double the other widens to match) and the result type follows the wider operand. So 5/2 is 3 (int math) while 5.0/2 is 2.5. Multiplication, division and remainder bind tighter than addition and subtraction; parentheses override that precedence.

code

java · 11 lines
java
int a = 5, b = 2;
System.out.println(a + b);   // 7
System.out.println(a - b);   // 3
System.out.println(a * b);   // 10
System.out.println(a / b);   // 2  (integer division)
System.out.println(a % b);   // 1  (remainder)
System.out.println(-a);      // -5 (unary minus)

System.out.println(5.0 / 2); // 2.5 (one double -> double math)
System.out.println(1 + 2 + "x"); // "3x"  (+ adds, then concatenates)
System.out.println("x" + 1 + 2); // "x12" (left-to-right concatenation)

go deeper

for a junior

Names all five binary operators plus unary minus, and knows 5/2 is 2 because both are ints.

for a middle

Explains numeric promotion and that the result type is the widest operand; predicts the + overloading and concatenation order.

for a senior

Distinguishes int vs float divide-by-zero, mentions silent integer overflow vs floating-point precision loss, and reasons about precedence/associativity cleanly.

for a principal

Frames the rules in terms of the JLS numeric-promotion model and can advise on safe-arithmetic patterns (Math.*Exact, BigDecimal) at a codebase/standards level.

## What 'arithmetic operators' means An **operator** is a symbol that tells the compiler to compute something from one or more values, called **operands**. **Arithmetic operators** do basic math on numbers. Java has five **binary** arithmetic operators (binary = two operands, one on each side): | Operator | Name | `7 ? 2` | |---|---|---| | `+` | addition | `9` | | `-` | subtraction | `5` | | `*` | multiplication | `14` | | `/` | division | `3` (see below) | | `%` | remainder (modulo) | `1` | And two **unary** arithmetic operators (unary = one operand): - **Unary minus** `-x` negates: `-5` is negative five; `-(x)` flips the sign of whatever `x` holds. - **Unary plus** `+x` does nothing useful to the value; it exists for symmetry. (One subtle effect: it forces numeric promotion, so `+aByte` has type `int`.) ## Two facts every junior trips on 1. **`+` is overloaded.** With numbers it adds; if *either* operand is a `String`, `+` means **String concatenation** and the result is a `String`. `1 + 2 + "x"` is `"3x"` (left-to-right: `1+2=3`, then `3 + "x"`), but `"x" + 1 + 2` is `"x12"`. 2. **The result type depends on the operands, not on the variable you store into.** Before computing, Java applies **numeric promotion**: `byte`, `short`, `char` are widened to `int`; then if either operand is `long`/`float`/`double`, the narrower one is widened to match. The operation is done in that widest type, and that is the type of the result. So `5 / 2` is **integer division** giving `3`, while `5.0 / 2` is `2.5`. Storing an `int` result into a `double` variable (`double d = 5/2;`) still gives `3.0` because the division already happened in `int`. ## Precedence and associativity `*`, `/`, `%` have **higher precedence** than `+`, `-`. So `2 + 3 * 4` is `14`, not `20`. Unary `+`/`-` bind tighter than all of them. All binary arithmetic operators are **left-associative**: `a - b - c` is `(a - b) - c`. Use parentheses to make intent explicit and to override precedence. ## Edge behaviour to remember - Integer `/` by zero throws `ArithmeticException`; floating-point `/` by zero gives `Infinity`/`NaN`, never an exception. - Integer arithmetic **wraps around** silently on overflow (it does not throw); floating-point can lose precision. With these rules you can predict the value *and* the type of any arithmetic expression.

  • Why does `double d = 5 / 2;` print 2.0 instead of 2.5?
    Both operands are int, so the division happens in int arithmetic and yields 2; that 2 is then widened to 2.0 when assigned to the double. To get 2.5, make one operand a double, e.g. 5.0 / 2 or (double) 5 / 2.
  • What is the result and type of `'A' + 1`?
    66 of type int. char 'A' is promoted to its code point 65, then + adds 1 in int arithmetic. To get the String "A1" you'd write "" + 'A' + 1.

Think of the operands as deciding the 'currency' of the result: mix in even one double and the whole expression is paid out in doubles; all-int means integer-only change, with the cents (the fraction) thrown away.

saying these in an interview costs you the question

  • Thinking the result type comes from the variable you assign to, rather than from the operands
  • Believing 5/2 returns 2.5 in Java
  • Assuming + always means addition (forgetting String concatenation)
  • Thinking integer overflow throws an exception

context

open as a page

What is the simple assignment operator (=) in Java, and what does an assignment expression evaluate to?

level: juniorimportance: must knowfreq 55%

basics

~20 s

The = operator stores the value on its right into the variable on its left. An assignment is also an expression whose result is the value that was assigned, so you can write a = b = 5 and both become 5.

open as a page

What do Java's bitwise operators &, |, ^, and ~ do, and how do they differ from the logical operators && and ||?

level: juniorimportance: must knowfreq 62%

basics

~20 s

&, |, ^ compare two numbers bit by bit (AND, OR, XOR); ~ flips every bit. They work on whole numbers. && and || work on true/false, only look at the second value if needed, and give back true or false.

open as a page

What does the instanceof operator do in Java, and what type of value does it produce?

level: juniorimportance: must knowfreq 78%

basics

~10 s

instanceof checks whether an object is an instance of a given type (class or interface). It returns a boolean: true if the object's type matches that type or a subtype, otherwise false.

open as a page

What are Java's logical operators &&, ||, and !, and what does each do?

level: juniorimportance: must knowfreq 70%

basics

~20 s

&& is logical AND: true only if both sides are true. || is logical OR: true if at least one side is true. ! is NOT: it flips a boolean, turning true into false and false into true.

open as a page

Explain short-circuit evaluation with && and ||, and give a practical reason it matters.

level: juniorimportance: must knowfreq 80%

basics

~20 s

With && and ||, Java checks the left side first and skips the right side if the answer is already known. false && X stays false without running X; true || X stays true without running X. This lets you safely null-check before using a value.

open as a page

What is operator precedence in Java, and why does it matter when you write expressions without parentheses?

level: juniorimportance: must knowfreq 60%

basics

~20 s

Operator precedence is the set of rules that decides which operators run first in an expression that has no parentheses. For example, * runs before +, so 2 + 3 * 4 is 14, not 20.

open as a page

What are Java's relational and equality operators, and what do they evaluate to?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Relational operators are <, <=, >, >= and equality operators are == and !=. They compare two values and always produce a boolean: true or false.

open as a page

What is the ternary conditional operator (?:) in Java, and how does it work?

level: juniorimportance: must knowfreq 70%

basics

~20 s

It's a one-line if/else that produces a value. You write condition ? a : b: if the condition is true you get a, otherwise b. It's an expression, so its result can be assigned or returned.

open as a page

How does integer division work in Java, and how does division-by-zero behave for integers versus floating-point?

level: middleimportance: must knowfreq 65%

basics

~20 s

When both operands are whole numbers, / drops the fraction and rounds toward zero, so 7/2 is 3 and -7/2 is -3. Dividing an integer by 0 throws an error; dividing a double by 0.0 gives Infinity or NaN.

open as a page

Explain the implicit narrowing cast performed by compound assignment, and give a case where it silently changes a value.

level: middleimportance: must knowfreq 58%

basics

~20 s

Compound assignment automatically casts the result back to the variable's type, like b += 1 meaning b = (byte)(b + 1). That hidden cast can quietly chop or wrap a value — e.g. byte b = 127; b += 1; makes b -128 with no error.

open as a page

Explain Java's three shift operators <<, >>, and >>> and how they differ.

level: middleimportance: must knowfreq 58%

basics

~20 s

<< moves bits left (filling zeros on the right), multiplying by powers of two. >> moves bits right keeping the sign (negatives stay negative). >>> moves bits right but always fills zeros on the left, ignoring the sign.

open as a page

What does instanceof return when the left-hand operand is null, and why is this behavior useful?

level: middleimportance: must knowfreq 70%

basics

~10 s

If the reference is null, instanceof always returns false (for any type). It never throws a NullPointerException. This makes it a safe combined null-and-type check.

open as a page

What is operator associativity, and how does it differ from precedence? Give an example where assignment's associativity matters.

level: middleimportance: must knowfreq 55%

basics

~20 s

Associativity decides the grouping when operators have the same precedence. Most operators group left to right (a - b - c is (a - b) - c). Assignment groups right to left, so a = b = 0 sets b to 0 first, then a.

open as a page

How do == and the relational operators behave when comparing primitive values, including mixed numeric types?

level: middleimportance: must knowfreq 60%

basics

~20 s

For primitives, == checks if the two values are equal and the relational operators compare their size. If the two operands are different number types, the smaller one is converted up to the larger type before comparing.

open as a page

What is the difference between == and .equals() when comparing objects in Java?

level: middleimportance: must knowfreq 95%

basics

~20 s

For objects, == checks whether two variables point to the very same object (identity). .equals() checks whether two objects are meaningfully equal in content. Use .equals() for value comparison, like comparing the text of two Strings.

open as a page

How can a ternary expression throw a NullPointerException even though neither branch is dereferenced? Explain the Integer/int unboxing trap.

level: seniorimportance: must knowfreq 60%

basics

~20 s

If one branch is a primitive (like int) and the other is a wrapper (like Integer), Java makes both numeric, so it unboxes the wrapper. If that wrapper is null, unboxing it throws a NullPointerException — even though you only have a number on the other side.

open as a page

What is the difference between prefix and postfix increment/decrement (++x vs x++) in Java?

level: juniorimportance: should knowfreq 60%

basics

~20 s

Both add 1 to the variable. The difference is the value the expression gives: ++x increments first and returns the new value; x++ returns the old value and then increments. Used alone on a line they behave the same.

open as a page

What are compound assignment operators like += and -=, and how does `x += y` differ from `x = x + y`?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Compound operators combine an operation with assignment: x += y means roughly x = x + y. Java has +=, -=, *=, /=, %=, and the bitwise/shift ones. They are shorthand and evaluate the left side only once.

open as a page

What does the % operator return in Java, and how does the sign of the result behave for negative operands and for floating-point values?

level: middleimportance: should knowfreq 55%

basics

~20 s

% gives the remainder after division. In Java the result takes the sign of the left operand (the dividend), so -7 % 3 is -1, not 2. It also works on doubles: 5.5 % 2 is 1.5.

open as a page

What does it mean to assign to a final variable, and how does final interact with assigning references vs. mutating objects?

level: middleimportance: should knowfreq 30%

basics

~20 s

A final variable can be assigned only once. After that you can't reassign it. But final only locks the variable, not the object it points to — you can still change the object's contents through that reference.

open as a page

How do you use bitwise operators to implement a set of boolean flags packed into a single int, and what operations set, clear, toggle, and test a flag?

level: middleimportance: should knowfreq 48%

basics

~20 s

Give each flag its own bit (1, 2, 4, 8...). Use | to turn a flag on, & with the mask to test it, &~ to turn it off, and ^ to flip it. One int can hold up to 32 flags.

open as a page

What is pattern matching for instanceof (Java 16+), and what advantages does it bring over the classic test-then-cast idiom?

level: middleimportance: should knowfreq 62%

basics

~20 s

Pattern matching lets you write if (obj instanceof String s). If the test passes, it automatically casts obj and binds it to a new variable s, so you skip the manual cast. It removes boilerplate and the chance of casting to the wrong type.

open as a page

What is the difference between && / || and the boolean & / | operators in Java?

level: middleimportance: should knowfreq 65%

basics

~20 s

&& and || stop early (short-circuit): they skip the right side once the answer is known. & and | on booleans give the same true/false result but always evaluate BOTH sides. On integers, & and | are bitwise operators instead.

open as a page

What does the ^ operator do when both operands are boolean, and when is logical XOR useful?

level: middleimportance: should knowfreq 40%

basics

~20 s

On two booleans, ^ is logical XOR (exclusive or): it is true when the two values are different, and false when they are the same. It's handy to test 'exactly one of these is true'.

open as a page

Why does an expression like flags & MASK == 0 often behave unexpectedly in Java, and how does the precedence table explain it?

level: middleimportance: should knowfreq 40%

basics

~20 s

Because == has higher precedence than &, Java reads it as flags & (MASK == 0), not (flags & MASK) == 0. The comparison runs first, which is almost never what you meant. Add parentheses: (flags & MASK) == 0.

open as a page

How does Java determine the result type of a ternary when the two branches are different numeric types?

level: middleimportance: should knowfreq 55%

basics

~20 s

Java picks one common type for the whole expression. With two different number types it usually promotes both to the wider one (for example int and double become double), so the ternary's result is that wider type — even on the branch that wasn't taken.

open as a page

When should you prefer a ternary over an if/else, and what are the readability and correctness pitfalls a senior engineer should police in code review?

level: middleimportance: should knowfreq 45%

basics

~20 s

Use a ternary for short, simple value selection (assign or return one of two values). Avoid it for side effects or when nesting many conditions — that gets hard to read. For anything complex, an if/else is clearer.

open as a page

Why do `int` arithmetic and `double` arithmetic produce surprising results (silent overflow, lost precision), and how should you guard against them?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Whole-number math wraps around silently when it gets too big (e.g. a huge int can suddenly go negative). Decimal math (double) can't represent some values exactly, so 0.1 + 0.2 isn't exactly 0.3. Use bigger types, Math.*Exact, or BigDecimal to stay safe.

open as a page

In a compound assignment to an array element or field, what is the evaluation order, and why can it matter?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Java evaluates the target's location (like the array reference and index) first and only once, then reads the old value, applies the operation with the right-hand side, and stores back. So a method used to pick the slot runs a single time.

open as a page

showing 1–30 of 40