Operators in Java – Types and Precedence with Examples
An operator is a symbol that tells Java to perform an operation on one or more values, called operands. In price * quantity, the operator * multiplies the operands price and quantity. Operators are how Java calculates, compares, makes decisions and changes variables.
This overview introduces every category of Java operator with a quick example, then explains precedence: the rules that decide which operator runs first. Each category also has its own detailed tutorial.
1. What Is an Operator?
An operator plus its operands forms an expression that produces a value. Operators are classified by the number of operands they take:
- Unary operators take one operand:
-x,!done,count++. - Binary operators take two:
a + b,x > y. - Ternary operator takes three:
condition ? a : b.
2. Types of Operators
| Category | Operators | Example |
|---|---|---|
| Arithmetic | + - * / % | total = price * qty; |
| Unary | + - ++ -- ! ~ | count++; |
| Assignment | = += -= *= /= %= &= |= ^= <<= >>= >>>= | score += 10; |
| Relational | == != > < >= <= | age >= 18 |
| Logical | && || ! | isMember && hasCoupon |
| Bitwise and shift | & | ^ ~ << >> >>> | flags & MASK |
| Ternary | ? : | max = a > b ? a : b; |
| Type comparison | instanceof | obj instanceof String s |
| Other | . (member access), [] (array index), () (call/cast), -> (lambda), :: (method reference), new | list.get(0) |
3. All Categories in One Program
public class OperatorTour {
public static void main(String[] args) {
int a = 17, b = 5;
// Arithmetic
System.out.println("a + b = " + (a + b) + ", a - b = " + (a - b) + ", a * b = " + (a * b)
+ ", a / b = " + (a / b) + ", a % b = " + (a % b));
// Unary
int c = a;
System.out.println("-c = " + (-c) + ", ++c = " + (++c) + ", !true = " + !true);
// Assignment
int total = 100;
total += 20;
total *= 2;
System.out.println("total = " + total);
// Relational
System.out.println("a > b: " + (a > b) + ", a == b: " + (a == b) + ", a != b: " + (a != b));
// Logical
boolean hasTicket = true, isAdult = false;
System.out.println("hasTicket && isAdult: " + (hasTicket && isAdult) + ", hasTicket || isAdult: " + (hasTicket || isAdult));
// Bitwise and shift
System.out.println("6 & 3 = " + (6 & 3) + ", 6 | 3 = " + (6 | 3) + ", 6 ^ 3 = " + (6 ^ 3) + ", 1 << 4 = " + (1 << 4));
// Ternary
String result = a % 2 == 0 ? "even" : "odd";
System.out.println(a + " is " + result);
// instanceof
Object o = "text";
System.out.println("o instanceof String: " + (o instanceof String));
}
}
a + b = 22, a - b = 12, a * b = 85, a / b = 3, a % b = 2 -c = -17, ++c = 18, !true = false total = 240 a > b: true, a == b: false, a != b: true hasTicket && isAdult: false, hasTicket || isAdult: true 6 & 3 = 2, 6 | 3 = 7, 6 ^ 3 = 5, 1 << 4 = 16 17 is odd o instanceof String: true
Notice that 17 / 5 is 3: dividing two integers drops the remainder, which % returns.
4. Arithmetic Operators
+, -, *, / and % work on numbers. + also joins strings. Integer division truncates, and dividing an integer by zero throws ArithmeticException, while floating-point division by zero gives Infinity.
5. Unary Operators
Unary operators act on one value: - negates, ++ and -- add or subtract one, ! flips a boolean, and ~ flips all bits. The position of ++ matters: ++x changes x before its value is used, x++ after.
6. Assignment Operators
= stores a value. Compound operators such as += combine an operation with assignment, and they include an automatic cast: byte b = 10; b += 5; compiles, while b = b + 5; does not.
7. Relational Operators
Relational operators compare values and return true or false. For objects, == compares references, not content; use equals() to compare strings and other objects.
8. Logical Operators
&& (AND), || (OR) and ! (NOT) combine boolean conditions. && and || short-circuit: if the left side already decides the result, the right side is not evaluated, which makes checks like s != null && s.isEmpty() safe.
9. Bitwise and Shift Operators
These work on the individual bits of integers: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (signed right shift) and >>> (unsigned right shift). They are used for flags, masks, hashing and low-level performance tricks.
10. Ternary Operator
condition ? valueIfTrue : valueIfFalse is a compact if-else that produces a value. It is ideal for simple choices such as String label = stock > 0 ? "In stock" : "Sold out";.
11. Operator Precedence and Associativity
When an expression has several operators, precedence decides which runs first (like multiplication before addition in maths), and associativity decides the order for operators of equal precedence.
public class PrecedenceDemo {
public static void main(String[] args) {
System.out.println("2 + 3 * 4 = " + (2 + 3 * 4)); // * before +
System.out.println("(2 + 3) * 4 = " + ((2 + 3) * 4)); // parentheses first
System.out.println("10 - 4 - 3 = " + (10 - 4 - 3)); // left to right
System.out.println("100 / 10 / 5 = " + (100 / 10 / 5)); // left to right
System.out.println("2 + 3 > 4 && 1 < 0 = " + (2 + 3 > 4 && 1 < 0));
int x, y;
x = y = 7; // assignment: right to left
System.out.println("x = " + x + ", y = " + y);
System.out.println("Sum: " + 2 + 3); // string concatenation first
System.out.println("Sum: " + (2 + 3)); // brackets fix it
}
}
2 + 3 * 4 = 14 (2 + 3) * 4 = 20 10 - 4 - 3 = 3 100 / 10 / 5 = 2 2 + 3 > 4 && 1 < 0 = false x = 7, y = 7 Sum: 23 Sum: 5
The last two lines show a classic trap: "Sum: " + 2 + 3 is evaluated left to right, so 2 is joined to the string first, then 3.
| Precedence (high to low) | Operators | Associativity |
|---|---|---|
| 1. Postfix | x++ x-- | Left to right |
| 2. Unary | ++x --x +x -x ! ~ (type) | Right to left |
| 3. Multiplicative | * / % | Left to right |
| 4. Additive | + - | Left to right |
| 5. Shift | << >> >>> | Left to right |
| 6. Relational | < > <= >= instanceof | Left to right |
| 7. Equality | == != | Left to right |
| 8. Bitwise AND | & | Left to right |
| 9. Bitwise XOR | ^ | Left to right |
| 10. Bitwise OR | | | Left to right |
| 11. Logical AND | && | Left to right |
| 12. Logical OR | || | Left to right |
| 13. Ternary | ? : | Right to left |
| 14. Assignment and lambda | = += -= *= /= %= &= ^= |= <<= >>= >>>= -> | Right to left |
12. Evaluation Order of Operands
Java guarantees that operands are evaluated left to right, and that all operands are evaluated before the operator is applied (except for the short-circuit operators and the ternary operator). This makes expressions with side effects, such as method calls, predictable, but code is still clearer when each statement does one thing.
13. Summary
- Operators act on operands to form expressions; they can be unary, binary or ternary.
- Categories: arithmetic, unary, assignment, relational, logical, bitwise/shift, ternary and
instanceof. - Precedence and associativity decide the order of evaluation; parentheses override them.
- Watch for integer division,
==on objects and string concatenation order.
Related Tutorials
Reference: dev.java: Using Operators
Frequently Asked Questions (FAQ)
Q1. What is an operator in Java?
A symbol that performs an operation on one or more operands and produces a result, such as + for addition, == for comparison or && for logical AND.
Q2. How many types of operators does Java have?
The main categories are arithmetic, unary, assignment, relational, logical, bitwise and shift, ternary, and the instanceof type comparison operator.
Q3. What is operator precedence?
The rule that decides which operator is applied first in an expression with several operators. For example, * has higher precedence than +, so 2 + 3 * 4 is 14.
Q4. What is associativity?
The direction in which operators of equal precedence are grouped. Most binary operators are left-associative (10 - 4 - 3 is (10 - 4) - 3); assignment and the ternary operator are right-associative.
Q5. Which operator has the highest precedence?
Postfix operators (x++, x--), together with member access, array indexing and method calls. Assignment operators have the lowest.
Q6. What is the difference between = and ==?
= assigns a value to a variable. == compares two values and returns true or false.
Q7. Why does 7 / 2 give 3 in Java?
Both operands are integers, so Java performs integer division and discards the fractional part. Use 7 / 2.0 or cast one operand to double to get 3.5.
Q8. What is the modulus operator?
% returns the remainder of a division: 17 % 5 is 2. It is often used to check even/odd numbers or to wrap values around a range.
Q9. What is short-circuit evaluation?
With && and ||, Java skips the right operand if the left one already decides the result. For example, in obj != null && obj.isValid(), isValid() is never called on null.
Q10. What is the difference between && and &?
For booleans, both compute AND, but && short-circuits while & always evaluates both sides. For integers, & is a bitwise AND.
Q11. Does Java support operator overloading?
No, you cannot define operators for your own classes. The only built-in overload is + for string concatenation.
Q12. What is the ternary operator?
The only operator with three operands: condition ? a : b. It returns a if the condition is true, otherwise b.
Q13. Is instanceof an operator?
Yes. It checks whether an object is an instance of a class or interface and returns a boolean. Since Java 16 it can also declare a pattern variable.
Q14. Why does "Sum: " + 2 + 3 print "Sum: 23"?
+ is evaluated left to right. "Sum: " + 2 becomes the string "Sum: 2", and adding 3 appends another character. Write "Sum: " + (2 + 3) to add the numbers first.
Q15. What is the difference between ++x and x++?
Both add one to x. ++x (pre-increment) returns the new value; x++ (post-increment) returns the old value. The difference matters only when the expression's value is used.
Q16. Can I compare strings with ==?
You should not. == compares object references. Use s1.equals(s2) to compare the text of two strings.
Q17. What does the >>> operator do?
It is the unsigned right shift: it shifts bits right and fills the left side with zeros, regardless of sign. >> fills with copies of the sign bit.
Q18. What is the order of evaluation of operands in Java?
Left to right. In a() + b(), a() is always called before b(), unlike in C where the order is unspecified.
Q19. Are -> and :: operators?
They are separators used for lambdas (x -> x * 2) and method references (String::length). They are often listed with operators because they appear in expressions.
Q20. Should I rely on precedence rules or use parentheses?
Use parentheses whenever an expression mixes several kinds of operators. They make the intended order obvious and prevent subtle bugs.