Operators in Java
Learn Java operators in detail, including arithmetic, unary, assignment, relational, logical, bitwise, shift, ternary, instanceof, operator precedence, associativity, expressions, common errors, and best practices.
Introduction
In the previous lessons, you learned how variables store values, how constants protect values from reassignment, and how data types define the kind of data a variable can contain. The next step is learning how to perform operations on those values.
Operators are special symbols that instruct Java to perform calculations, comparisons, assignments, logical decisions, bit manipulation, and other operations.
int first = 10;
int second = 5;
int sum = first + second;
boolean greater = first > second;
boolean valid = first > 0 && second > 0;
first++;VALUE
│
▼
OPERATOR
│
▼
OPERATION
│
▼
RESULT- What an operator is.
- Why operators are needed.
- What operands are.
- What expressions are.
- The major categories of Java operators.
- How arithmetic operators work.
- How addition works.
- How subtraction works.
- How multiplication works.
- How division works.
- The difference between integer and floating-point division.
- What happens during division by zero.
- How the modulus operator works.
- How unary operators work.
- How increment and decrement operators work.
- The difference between prefix and postfix forms.
- How assignment operators work.
- How compound assignment works.
- How relational operators compare values.
- How equality works with primitives and references.
- How to compare Strings correctly.
- How logical operators work.
- How short-circuit evaluation works.
- How bitwise operators work.
- How shift operators work.
- How the ternary operator works.
- How instanceof works.
- How pattern matching with instanceof works.
- How the + operator performs String concatenation.
- How operator precedence works.
- How associativity works.
- How parentheses control evaluation.
- How numeric promotion affects expressions.
- How mixed-type expressions are evaluated.
- How overflow can occur inside expressions.
- Common operator errors.
- Best practices for writing clear expressions.
What is an Operator?
An operator is a symbol that tells Java to perform a specific operation on one or more values.
int result = 10 + 5;10 + 5
│ │ │
│ │ └── Operand
│ │
│ └───── Operator
│
└──────── OperandIn the expression 10 + 5, the values 10 and 5 are operands, while + is the operator.
Why Operators are Needed
Calculations
Operators perform mathematical calculations such as addition, subtraction, multiplication, and division.
Comparisons
Operators compare values and produce boolean results.
Assignment
Operators store and update values in variables.
Decisions
Logical operators combine conditions used in program decisions.
Bit Manipulation
Bitwise and shift operators work directly with binary representations.
Compact Expressions
Operators allow complex operations to be expressed clearly and efficiently.
Real-World Analogy
Think of an operator as an instruction given to a calculator. The values are the inputs, the operator defines the action, and the expression produces a result.
10 + 5
INPUT OPERATION INPUT
│
▼
15
RESULTOperands and Expressions
An operand is a value or variable on which an operator acts. An expression is a combination of operands and operators that produces a value.
int result = 10 + 5;
int total = result * 2;
boolean valid = total > 20;10 + 5
│
▼
15
15 * 2
│
▼
30
30 > 20
│
▼
trueOperator Categories
JAVA OPERATORS
├── Arithmetic Operators
├── Unary Operators
├── Assignment Operators
├── Relational Operators
├── Logical Operators
├── Bitwise Operators
├── Shift Operators
├── Ternary Operator
└── instanceof OperatorArithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values.
OPERATOR OPERATION
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainderint a = 10;
int b = 3;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);Addition Operator
The + operator adds numeric values. It is also used for String concatenation.
int first = 10;
int second = 5;
int result = first + second;
System.out.println(result);15Subtraction Operator
The - operator subtracts the right operand from the left operand.
int first = 10;
int second = 5;
int result = first - second;
System.out.println(result);5Multiplication Operator
The * operator multiplies two numeric operands.
int quantity = 5;
int price = 100;
int total = quantity * price;
System.out.println(total);500Division Operator
The / operator divides the left operand by the right operand. The result depends on the operand types.
int result = 10 / 2;
System.out.println(result);5Integer Division
When both operands are integer types, Java performs integer division. The fractional part is discarded.
int result = 10 / 3;
System.out.println(result);310 / 3
Mathematical Result:
3.333...
Integer Division Result:
3- Integer division does not round the result.
- The fractional part is discarded.
- Use a floating-point operand when a decimal result is required.
Floating-Point Division
If at least one operand is a floating-point value, Java performs floating-point division.
double first = 10.0;
int second = 3;
double result = first / second;
System.out.println(result);3.3333333333333335double result = 10.0 / 3;
System.out.println(result);Division by Zero
The result of division by zero depends on whether the operation uses integer arithmetic or floating-point arithmetic.
int number = 10;
int zero = 0;
// int result = number / zero;
// ArithmeticExceptiondouble positive = 10.0 / 0.0;
double negative = -10.0 / 0.0;
double undefined = 0.0 / 0.0;
System.out.println(positive);
System.out.println(negative);
System.out.println(undefined);Infinity
-Infinity
NaN- Integer division by zero throws ArithmeticException.
- Floating-point division by positive zero can produce Infinity.
- Floating-point division by negative zero can produce signed infinity.
- Zero divided by zero in floating-point arithmetic produces NaN.
Modulus Operator
The % operator returns the remainder after division.
int result = 10 % 3;
System.out.println(result);10 ÷ 3
Quotient = 3
Remainder = 1
10 % 3 = 1int number = 10;
boolean even = number % 2 == 0;
System.out.println(even);Arithmetic Examples
int a = 20;
int b = 6;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Remainder: " + (a % b));Addition: 26
Subtraction: 14
Multiplication: 120
Division: 3
Remainder: 2Unary Operators
Unary operators operate on a single operand.
OPERATOR PURPOSE
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical NOT
~ Bitwise complementUnary Plus
The unary + operator indicates a positive numeric value.
int number = 10;
int result = +number;
System.out.println(result);10Unary Minus
The unary - operator negates a numeric value.
int number = 10;
int result = -number;
System.out.println(result);-10Increment Operator
The ++ operator increases a variable by 1.
int count = 10;
count++;
System.out.println(count);11Decrement Operator
The -- operator decreases a variable by 1.
int count = 10;
count--;
System.out.println(count);9Prefix Increment
With prefix increment, the variable is incremented before its value is used in the surrounding expression.
int number = 5;
int result = ++number;
System.out.println(number);
System.out.println(result);number = 5
++number
1. Increment number to 6
2. Use value 6
result = 6Postfix Increment
With postfix increment, the current value is used first and the variable is incremented afterward.
int number = 5;
int result = number++;
System.out.println(number);
System.out.println(result);number = 5
number++
1. Use value 5
2. Increment number to 6
result = 5Prefix vs Postfix
PREFIX
int x = 5;
int y = ++x;
x = 6
y = 6
POSTFIX
int x = 5;
int y = x++;
x = 6
y = 5- Prefix changes the value before it is used.
- Postfix uses the old value before changing it.
- Complex expressions containing multiple increments are difficult to read.
- Prefer separate statements when evaluation order is not immediately obvious.
Logical NOT
The ! operator reverses a boolean value.
boolean active = true;
boolean inactive = !active;
System.out.println(inactive);VALUE !VALUE
true false
false trueBitwise Complement
The ~ operator flips every bit of an integer value.
int number = 5;
int result = ~number;
System.out.println(result);-6For integer values, the result follows the two’s-complement relationship ~x equals -(x + 1).
Assignment Operators
Assignment operators store or update values in variables.
OPERATOR EXAMPLE
= x = 10
+= x += 5
-= x -= 5
*= x *= 5
/= x /= 5
%= x %= 5
&= x &= 5
|= x |= 5
^= x ^= 5
<<= x <<= 1
>>= x >>= 1
>>>= x >>>= 1Simple Assignment
int number;
number = 10;
System.out.println(number);number = 10;
◄──────
Value on the right
is assigned to
variable on the leftCompound Assignment
Compound assignment combines an operation with assignment.
int number = 10;
number += 5;
System.out.println(number);number += 5;
Similar purpose:
number = number + 5;Addition Assignment
int score = 100;
score += 50;
System.out.println(score);150Subtraction Assignment
int balance = 1000;
balance -= 200;
System.out.println(balance);800Multiplication Assignment
int number = 5;
number *= 4;
System.out.println(number);20Division Assignment
int number = 20;
number /= 4;
System.out.println(number);5Modulus Assignment
int number = 10;
number %= 3;
System.out.println(number);1Compound Assignment and Implicit Conversion
Compound assignment includes an implicit conversion back to the type of the left-hand variable.
byte value = 10;
value += 5;
System.out.println(value);byte value = 10;
// value = value + 5;
// Compilation error
value = (byte) (value + 5);- value += expression includes an implicit conversion to the type of value.
- value = value + expression may require an explicit cast.
- The implicit conversion can potentially lose information.
- Use compound assignment carefully with smaller numeric types.
Relational Operators
Relational operators compare values and produce a boolean result.
OPERATOR MEANING
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal toEqual To Operator
int first = 10;
int second = 10;
boolean result = first == second;
System.out.println(result);trueNot Equal To Operator
int first = 10;
int second = 5;
boolean result = first != second;
System.out.println(result);trueGreater Than Operator
int age = 25;
boolean result = age > 18;
System.out.println(result);Less Than Operator
int temperature = 10;
boolean cold = temperature < 15;
System.out.println(cold);Greater Than or Equal To Operator
int age = 18;
boolean eligible = age >= 18;
System.out.println(eligible);Less Than or Equal To Operator
int score = 40;
boolean failed = score <= 40;
System.out.println(failed);Comparing Primitive Values
For compatible primitive values, comparison operators compare the represented values.
int first = 10;
int second = 10;
System.out.println(first == second);
double price = 99.99;
System.out.println(price > 50.0);Comparing References
When == is used with reference variables, it checks whether both references refer to the same object.
String first = new String("Java");
String second = new String("Java");
System.out.println(first == second);falsefirst ─────► "Java" Object 1
second ────► "Java" Object 2
Different Objects
first == second
falseComparing Strings
Use equals() when you want to compare String content.
String first = new String("Java");
String second = new String("Java");
System.out.println(first.equals(second));true- == compares primitive values when used with compatible primitives.
- == compares reference identity when used with references.
- equals() is commonly used to compare object content when the class defines value equality.
- Use equals() for String content comparison.
Logical Operators
Logical operators work with boolean expressions.
OPERATOR MEANING
&& Logical AND
|| Logical OR
! Logical NOTLogical AND
The && operator produces true only when both operands are true.
A B A && B
false false false
false true false
true false false
true true trueint age = 25;
boolean hasId = true;
boolean allowed =
age >= 18 && hasId;
System.out.println(allowed);Logical OR
The || operator produces true when at least one operand is true.
A B A || B
false false false
false true true
true false true
true true trueboolean admin = false;
boolean owner = true;
boolean allowed =
admin || owner;
System.out.println(allowed);Logical NOT Operator
boolean loggedIn = false;
boolean guest = !loggedIn;
System.out.println(guest);Short-Circuit Evaluation
The && and || operators may skip evaluation of the right operand when the final result is already known.
false && anything
Result already known:
false
Right side skipped
true || anything
Result already known:
true
Right side skippedAND Short-Circuit
String name = null;
boolean valid =
name != null
&& name.length() > 3;
System.out.println(valid);name != null
false
│
▼
Second condition skipped
│
▼
falseOR Short-Circuit
boolean admin = true;
boolean allowed =
admin || checkPermission();
System.out.println(allowed);Because admin is already true, Java does not need to evaluate checkPermission() to determine the result.
Boolean & and | Operators
The & and | operators can also work with boolean operands, but unlike && and ||, they evaluate both operands.
boolean first = false;
boolean second = true;
System.out.println(first & second);
System.out.println(first | second);- && performs short-circuit logical AND.
- & evaluates both boolean operands.
- || performs short-circuit logical OR.
- | evaluates both boolean operands.
- For ordinary conditions, && and || are usually preferred.
Bitwise Operators
Bitwise operators work on the individual bits of integer values.
OPERATOR OPERATION
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complementBitwise AND
5 = 0101
3 = 0011
0101
& 0011
────────
0001
Result = 1int result = 5 & 3;
System.out.println(result);Bitwise OR
5 = 0101
3 = 0011
0101
| 0011
────────
0111
Result = 7int result = 5 | 3;
System.out.println(result);Bitwise XOR
The ^ operator produces 1 for each bit position where the corresponding operand bits are different.
5 = 0101
3 = 0011
0101
^ 0011
────────
0110
Result = 6int result = 5 ^ 3;
System.out.println(result);Bitwise Complement Operator
int number = 5;
int result = ~number;
System.out.println(result);~x = -(x + 1)
~5
= -(5 + 1)
= -6Binary Representation
Bitwise operations become easier to understand when values are written in binary.
int number = 10;
String binary =
Integer.toBinaryString(number);
System.out.println(binary);1010Shift Operators
Shift operators move the bits of an integer value left or right.
OPERATOR MEANING
<< Left shift
>> Signed right shift
>>> Unsigned right shiftLeft Shift
The << operator shifts bits to the left and fills the new low-order positions with zeros.
int number = 5;
int result = number << 1;
System.out.println(result);5
0101
Shift left by 1
1010
10Signed Right Shift
The >> operator shifts bits to the right while preserving the sign through sign extension.
int number = 20;
int result = number >> 2;
System.out.println(result);5Unsigned Right Shift
The >>> operator shifts bits to the right and fills the new high-order positions with zeros.
int number = -8;
int result = number >>> 1;
System.out.println(result);- >> preserves the sign through sign extension.
- >>> fills high-order positions with zeros.
- The difference is especially visible with negative values.
- Shift operations are commonly used in low-level data processing and bit manipulation.
Shift Examples
int number = 16;
System.out.println(number << 1);
System.out.println(number >> 1);
System.out.println(number >>> 1);32
8
8Ternary Operator
The conditional operator, commonly called the ternary operator, selects one of two expressions based on a boolean condition.
condition ? valueIfTrue : valueIfFalseTernary Syntax
int age = 20;
String result =
age >= 18
? "Adult"
: "Minor";
System.out.println(result);age >= 18
│
▼
true
│
▼
"Adult"Ternary Examples
int a = 10;
int b = 20;
int maximum =
a > b ? a : b;
System.out.println(maximum);int number = 7;
String result =
number % 2 == 0
? "Even"
: "Odd";
System.out.println(result);Nested Ternary Operator
int number = 0;
String result =
number > 0
? "Positive"
: number < 0
? "Negative"
: "Zero";
System.out.println(result);- Simple ternary expressions can improve readability.
- Deeply nested ternary expressions are difficult to understand.
- Use if-else statements when multiple conditions make the expression unclear.
instanceof Operator
The instanceof operator checks whether an object reference is compatible with a specified reference type.
Object value = "Java";
boolean result =
value instanceof String;
System.out.println(result);trueObject value = null;
System.out.println(
value instanceof String
);falsePattern Matching with instanceof
Modern Java allows instanceof to test a type and create a pattern variable in one operation.
Object value = "Java Programming";
if (value instanceof String text) {
System.out.println(text.length());
}OLD STYLE
Check type
│
▼
Cast manually
│
▼
Use value
PATTERN MATCHING
Check type
│
▼
Create typed variable
│
▼
Use valueString Concatenation
When one operand of + is a String, Java performs String concatenation.
String firstName = "Alex";
String lastName = "Smith";
String fullName =
firstName + " " + lastName;
System.out.println(fullName);Alex SmithString and Number Evaluation
The + operator is evaluated from left to right, so the position of a String can change the result.
System.out.println(10 + 20 + " Java");
System.out.println("Java " + 10 + 20);30 Java
Java 102010 + 20 + " Java"
30 + " Java"
"30 Java"
"Java " + 10 + 20
"Java 10" + 20
"Java 1020"System.out.println(
"Java " + (10 + 20)
);Java 30Operator Precedence
Operator precedence determines which operator is evaluated first when an expression contains multiple operators.
int result = 10 + 5 * 2;
System.out.println(result);10 + 5 * 2
Multiplication first:
5 * 2 = 10
Then addition:
10 + 10 = 20HIGHER PRECEDENCE
()
Postfix ++ --
Unary ++ -- + - ! ~
* / %
+ -
<< >> >>>
< <= > >= instanceof
== !=
&
^
|
&&
||
? :
Assignment
LOWER PRECEDENCEAssociativity
Associativity determines evaluation grouping when operators have the same precedence.
int result = 20 - 5 - 3;
System.out.println(result);20 - 5 - 3
│
▼
(20 - 5) - 3
│
▼
15 - 3
│
▼
12int a;
int b;
int c;
a = b = c = 10;a = b = c = 10
│
▼
c = 10
│
▼
b = 10
│
▼
a = 10Using Parentheses
Parentheses can change evaluation order and make complex expressions easier to understand.
int result = 10 + 5 * 2;
System.out.println(result);20int result = (10 + 5) * 2;
System.out.println(result);30- Use parentheses when they make evaluation order clearer.
- Do not force readers to memorize the entire precedence table.
- Clear expressions are easier to maintain and less likely to contain mistakes.
Expression Evaluation
int result =
10 + 5 * 2 - 4 / 2;
System.out.println(result);10 + 5 * 2 - 4 / 2
│
▼
10 + 10 - 2
│
▼
20 - 2
│
▼
18Numeric Promotion
Java promotes smaller integer types during arithmetic expressions.
byte first = 10;
byte second = 20;
// byte result = first + second;
// Compilation error
int result = first + second;byte + byte
│
▼
int + int
│
▼
int result- byte, short, and char operands are promoted during many arithmetic operations.
- If either operand is double, the operation uses double.
- Otherwise, if either operand is float, the operation uses float.
- Otherwise, if either operand is long, the operation uses long.
- Otherwise, integer arithmetic generally uses int.
Mixed-Type Expressions
int number = 10;
double price = 2.5;
double result = number * price;
System.out.println(result);int
10
│
▼
Promoted to double
10.0
│
▼
10.0 * 2.5
│
▼
25.0Overflow in Expressions
The type of the final variable does not automatically change the type used for an earlier arithmetic operation.
int first = 1_000_000;
int second = 1_000_000;
long result = first * second;
System.out.println(result);The multiplication is performed as int arithmetic before the result is assigned to long, so overflow can occur.
int first = 1_000_000;
int second = 1_000_000;
long result =
(long) first * second;
System.out.println(result);1000000000000- Assigning an int expression to long does not make the earlier arithmetic use long.
- Promote at least one operand before the operation.
- Consider overflow when multiplying or adding large values.
Common Operator Errors
OPERATOR ERRORS
├── Using = Instead of ==
├── Using == for String Content
├── Forgetting Integer Division Rules
├── Dividing Integer Values by Zero
├── Assuming Floating Point is Exact
├── Misunderstanding Prefix and Postfix
├── Writing Complex Increment Expressions
├── Confusing && with &
├── Confusing || with |
├── Ignoring Short-Circuit Behavior
├── Misunderstanding Operator Precedence
├── Forgetting Parentheses
├── Overflow Before long Assignment
├── Assuming byte + byte Produces byte
├── Misusing Nested Ternary Expressions
├── Confusing >> with >>>
└── Forgetting String Concatenation OrderString first = new String("Java");
String second = new String("Java");
// Wrong for content comparison
System.out.println(first == second);
// Correct
System.out.println(first.equals(second));double result = 10 / 3;
System.out.println(result);
// Output:
// 3.0double result = 10.0 / 3;
System.out.println(result);Best Practices
- Use operators only with compatible operand types.
- Use meaningful variable names around complex expressions.
- Keep arithmetic expressions readable.
- Use parentheses when evaluation order may not be obvious.
- Do not rely unnecessarily on memorized precedence rules.
- Understand the difference between integer and floating-point division.
- Use at least one floating-point operand when a decimal division result is required.
- Check divisors before integer division when zero is possible.
- Understand Infinity and NaN in floating-point arithmetic.
- Use the modulus operator for remainder-based logic.
- Use increment and decrement operators for simple changes by one.
- Avoid multiple increments or decrements inside one complex expression.
- Understand the difference between prefix and postfix forms.
- Use compound assignment when it improves readability.
- Remember that compound assignment includes an implicit conversion.
- Be careful with compound assignment on byte, short, and char.
- Use == for primitive value comparison.
- Use == for reference identity only when identity is what you intend to compare.
- Use equals() for String content comparison.
- Use null-safe comparison techniques where appropriate.
- Use && and || for ordinary boolean conditions.
- Use short-circuit evaluation deliberately.
- Place null checks before dereferencing values in && expressions.
- Understand that & and | evaluate both boolean operands.
- Use bitwise operators only when bit-level behavior is intended.
- Document non-obvious bit masks.
- Use binary literals when they improve bit-level readability.
- Understand the difference between signed and unsigned right shifts.
- Use the ternary operator for simple value selection.
- Avoid deeply nested ternary expressions.
- Use if-else when conditional logic becomes difficult to read.
- Use instanceof when checking reference type compatibility.
- Use pattern matching with instanceof when it simplifies safe type access.
- Remember that null instanceof any reference type is false.
- Understand that + performs String concatenation when a String operand is involved.
- Use parentheses when mixing numeric addition and String concatenation.
- Understand left-to-right evaluation for operators with equal precedence.
- Remember that assignment operators are right-associative.
- Understand numeric promotion.
- Remember that byte, short, and char arithmetic commonly produces int.
- Promote operands before arithmetic when a wider type is required.
- Do not assume assigning an int expression to long prevents earlier overflow.
- Consider overflow in large arithmetic calculations.
- Use Math.addExact, Math.subtractExact, and Math.multiplyExact when overflow detection is required.
- Avoid direct floating-point equality checks when approximation is involved.
- Keep boolean expressions simple.
- Extract complex conditions into clearly named boolean variables.
- Avoid unnecessary negation when a positive condition is clearer.
- Use one operator per conceptual step when debugging complex calculations.
- Test boundary values.
- Test zero and negative values.
- Test overflow-sensitive calculations.
- Test null-sensitive logical expressions.
- Prefer clarity over compactness.
- Do not use clever expressions that are difficult to maintain.
- Add comments for unusual bitwise logic.
- Keep side effects out of complex expressions when possible.
- Separate assignment from complicated calculations when readability improves.
- Use formatting to make long expressions understandable.
- Review operator precedence during code reviews.
- Use parentheses around intentionally grouped calculations.
- Avoid comparing unrelated reference types.
- Use domain-specific methods when an operator expression becomes too complex.
- Remember that operators are part of expressions, and expressions should communicate intent.
Operator Checklist
OPERATOR CHECKLIST
[ ] Correct operator selected
[ ] Operand types are compatible
[ ] Integer division behavior understood
[ ] Decimal division uses floating-point operand
[ ] Division by zero considered
[ ] Remainder logic tested
[ ] Prefix/postfix behavior understood
[ ] Complex increment expressions avoided
[ ] Compound assignment conversion understood
[ ] == used correctly
[ ] String content compared with equals()
[ ] Reference identity comparison intentional
[ ] && and || used for short-circuit logic
[ ] Null check placed before dereference
[ ] & and | used intentionally
[ ] Bitwise operations documented
[ ] Shift operator selected correctly
[ ] Ternary expression remains readable
[ ] instanceof used safely
[ ] String concatenation order checked
[ ] Operator precedence understood
[ ] Parentheses added where useful
[ ] Associativity considered
[ ] Numeric promotion considered
[ ] byte/short/char promotion considered
[ ] Overflow considered
[ ] Wider operand introduced before calculation
[ ] Floating-point precision considered
[ ] Complex conditions extracted when needed
[ ] Side effects kept simple
[ ] Boundary values tested
[ ] Expression clearly communicates intentCommon Misconceptions
- The = operator assigns a value; it does not compare equality.
- The == operator compares equality.
- Integer division discards the fractional part.
- Assigning integer division to double does not restore the discarded fraction.
- At least one floating-point operand is needed for floating-point division.
- Integer division by zero throws ArithmeticException.
- Floating-point division by zero follows IEEE 754 behavior.
- The % operator returns a remainder.
- Prefix and postfix increment are not always equivalent inside larger expressions.
- Prefix changes the value before use.
- Postfix uses the old value before changing it.
- Compound assignment can include implicit conversion.
- byte + byte normally produces int.
- == does not generally compare object content.
- String content should usually be compared with equals().
- && and || can skip the right operand.
- & and | evaluate both boolean operands.
- Bitwise operators are different from short-circuit logical operators.
- ^ means XOR; it is not exponentiation.
- Java has no exponentiation operator.
- Use Math.pow() for exponentiation calculations.
- >> and >>> are different for negative values.
- The ternary operator produces a value.
- Deeply nested ternary expressions are usually difficult to read.
- null instanceof Type is false.
- The + operator can perform either numeric addition or String concatenation.
- String concatenation evaluation order can change output.
- Multiplication has higher precedence than addition.
- Operators with equal precedence can have different associativity rules.
- Assignment is right-associative.
- Parentheses can change evaluation order.
- The destination variable type does not automatically control the type of earlier arithmetic.
- long result = intValue * intValue can overflow before assignment.
- One operand must be promoted before arithmetic when wider arithmetic is required.
- Floating-point equality can be affected by approximation.
- Complex expressions are not automatically better because they use fewer lines.
- Readable expressions are preferable to clever expressions.
Practice Exercises
- Create two integer variables.
- Calculate their sum.
- Calculate their difference.
- Calculate their product.
- Calculate their quotient.
- Calculate their remainder.
- Print every result.
- Calculate 10 / 3 using integers.
- Store the result in double.
- Observe the result.
- Calculate 10.0 / 3.
- Compare both outputs.
- Explain why they are different.
- Create an integer variable.
- Use the modulus operator.
- Create a boolean expression that checks whether the number is even.
- Print the result.
- Create a variable with value 5.
- Use prefix increment and store the result.
- Reset the variable.
- Use postfix increment and store the result.
- Print all values.
- Explain the difference.
- Create a score variable.
- Increase it using +=.
- Decrease it using -=.
- Multiply it using *=.
- Divide it using /=.
- Print the result after each operation.
- Create two integer variables.
- Compare them using ==.
- Compare them using !=.
- Compare them using >.
- Compare them using <.
- Compare them using >=.
- Compare them using <=.
- Print all results.
- Create an age variable.
- Create a hasPermission boolean.
- Use && to determine access.
- Use || with an admin variable.
- Use ! to reverse a boolean.
- Print every result.
- Create a null String reference.
- Check that it is not null before calling length().
- Use && so the second expression is skipped.
- Print the final boolean result.
- Explain why no exception occurs.
- Create values 5 and 3.
- Apply bitwise AND.
- Apply bitwise OR.
- Apply bitwise XOR.
- Print each result in decimal.
- Print each result in binary.
- Create an integer variable.
- Use the ternary operator to determine whether it is even or odd.
- Print the result.
- Repeat the exercise to determine the larger of two values.
- Evaluate 10 + 5 * 2.
- Evaluate (10 + 5) * 2.
- Print both results.
- Explain why the outputs are different.
- Create two int values containing 1,000,000.
- Multiply them and assign the result to long.
- Observe the incorrect result caused by overflow.
- Cast one operand to long before multiplication.
- Print the correct result.
- Explain why the cast must happen before the operation.
Common Interview Questions
What is an operator in Java?
An operator is a symbol that performs an operation on one or more operands.
What is an operand?
An operand is a value, variable, or expression on which an operator acts.
What is an expression?
An expression is a combination of values, variables, operators, and method calls that produces a value.
What are the arithmetic operators in Java?
+, -, *, /, and %.
What is integer division?
Integer division occurs when both operands are integer types. The fractional part of the mathematical result is discarded.
What does the modulus operator do?
The % operator returns the remainder of a division operation.
What is the difference between prefix and postfix increment?
Prefix increment changes the variable before its value is used, while postfix increment uses the current value before changing the variable.
What is compound assignment?
Compound assignment combines an operation and assignment, such as +=, -=, *=, /=, and %.
What is the difference between = and ==?
= performs assignment, while == performs equality comparison.
What does == compare for reference types?
It checks whether the references refer to the same object.
How should String content be compared?
String content should usually be compared using equals().
What is short-circuit evaluation?
Short-circuit evaluation allows && and || to skip the right operand when the final result is already known.
What is the difference between && and &?
&& short-circuits for boolean operands, while & evaluates both boolean operands and also acts as a bitwise operator for integer values.
What is the difference between || and |?
|| short-circuits for boolean operands, while | evaluates both boolean operands and also acts as a bitwise operator for integer values.
What does XOR do?
Bitwise XOR produces a 1 bit where corresponding operand bits are different.
What is the difference between >> and >>>?
>> performs signed right shift with sign extension, while >>> performs unsigned right shift and fills high-order positions with zeros.
What is the ternary operator?
The ternary operator selects one of two expressions based on a boolean condition using condition ? trueExpression : falseExpression.
What does instanceof do?
It checks whether an object reference is compatible with a specified reference type.
What is operator precedence?
Operator precedence determines which operators are evaluated first in an expression.
What is associativity?
Associativity determines grouping when operators have the same precedence.
Why does byte + byte produce int?
Java applies integer numeric promotion to byte, short, and char operands in many arithmetic expressions.
Can int multiplication overflow before assignment to long?
Yes. If both operands are int, multiplication occurs using int arithmetic before the result is assigned to long.
Frequently Asked Questions
Does Java have an exponent operator?
No. The ^ operator is bitwise XOR, not exponentiation. Math.pow() can be used for exponentiation calculations.
Why does 10 / 3 return 3?
Both operands are integers, so Java performs integer division and discards the fractional part.
Why does double result = 10 / 3 produce 3.0?
The integer division happens first and produces 3. That integer result is then converted to double as 3.0.
How can I get a decimal result from division?
Make at least one operand floating point, such as 10.0 / 3.
What happens when an integer is divided by zero?
Integer division by zero throws ArithmeticException.
What happens when a floating-point value is divided by zero?
Depending on the operands, the result can be Infinity, -Infinity, or NaN.
Can % be used with floating-point values?
Yes. Java supports the remainder operator with floating-point operands.
Is ++x faster than x++?
For ordinary primitive variables, choose based on required semantics and readability rather than assumed performance differences.
Can I use ++ with final variables?
No. Increment changes the variable value, so it cannot be applied to a final variable.
Can == compare Strings?
It can compare String references for identity, but it should not generally be used for String content comparison.
Why does "Java " + 10 + 20 produce Java 1020?
Evaluation proceeds left to right. Once String concatenation begins, subsequent values are converted to text and concatenated.
How can I make 10 + 20 evaluate before String concatenation?
Use parentheses: "Java " + (10 + 20).
Is the ternary operator a statement?
The conditional operator forms an expression that produces a value.
What does null instanceof String return?
false.
Should I memorize all operator precedence levels?
You should understand the major precedence rules, but use parentheses when they make the intended evaluation clearer.
Why does byte + byte not produce byte?
Because byte operands are promoted to int during many arithmetic operations.
Why can byte += 1 compile when byte = byte + 1 does not?
Compound assignment includes an implicit conversion back to the type of the left-hand variable.
Can logical operators work with integers?
The short-circuit operators && and || require boolean operands. The operators &, |, and ^ can work with both boolean and integer operands in different ways.
What should I learn after operators?
The next lesson covers input and output in Java.
Key Takeaways
- Operators perform operations on values and variables.
- Values used by operators are called operands.
- Expressions combine operands and operators to produce values.
- Java provides arithmetic, unary, assignment, relational, logical, bitwise, shift, ternary, and instanceof operators.
- The + operator performs addition.
- The - operator performs subtraction.
- The * operator performs multiplication.
- The / operator performs division.
- The % operator returns a remainder.
- Integer division discards the fractional part.
- Floating-point division requires at least one floating-point operand.
- Integer division by zero throws ArithmeticException.
- Floating-point division by zero follows IEEE 754 behavior.
- Unary operators operate on one operand.
- Unary + represents a positive numeric value.
- Unary - negates a numeric value.
- ++ increments a variable by one.
- -- decrements a variable by one.
- Prefix increment changes the value before use.
- Postfix increment uses the old value before changing it.
- ! reverses a boolean value.
- ~ flips integer bits.
- Assignment operators store and update values.
- = performs simple assignment.
- Compound assignment combines an operation with assignment.
- Compound assignment includes an implicit conversion to the left-hand type.
- Relational operators produce boolean results.
- == checks equality.
- != checks inequality.
- > checks greater than.
- < checks less than.
- >= checks greater than or equal to.
- <= checks less than or equal to.
- == compares primitive values for compatible primitive types.
- == compares reference identity for reference types.
- String content should usually be compared using equals().
- && performs logical AND with short-circuit evaluation.
- || performs logical OR with short-circuit evaluation.
- ! performs logical NOT.
- Short-circuit evaluation can skip the right operand.
- Short-circuit evaluation is useful for safe null checks.
- & and | evaluate both boolean operands.
- & performs bitwise AND on integer values.
- | performs bitwise OR on integer values.
- ^ performs bitwise XOR.
- ~ performs bitwise complement.
- << performs left shift.
- >> performs signed right shift.
- >>> performs unsigned right shift.
- The ternary operator selects one of two expressions.
- The ternary syntax is condition ? valueIfTrue : valueIfFalse.
- Nested ternary expressions should remain readable.
- instanceof checks reference type compatibility.
- null instanceof any reference type is false.
- Pattern matching with instanceof can create a typed variable.
- The + operator also performs String concatenation.
- String concatenation evaluation order matters.
- Operator precedence determines which operators are evaluated first.
- Associativity determines grouping among operators with equal precedence.
- Many binary operators are left-associative.
- Assignment operators are right-associative.
- Parentheses can change evaluation order.
- Parentheses can also improve readability.
- byte, short, and char values are promoted during many arithmetic operations.
- byte + byte normally produces int.
- Mixed numeric expressions use numeric promotion.
- If either operand is double, arithmetic generally uses double.
- Otherwise, if either operand is float, arithmetic generally uses float.
- Otherwise, if either operand is long, arithmetic generally uses long.
- Otherwise, integer arithmetic generally uses int.
- An expression can overflow before being assigned to a wider variable.
- Promote an operand before arithmetic when wider arithmetic is required.
- Readable expressions are better than unnecessarily clever expressions.
- Complex conditions should be simplified or extracted into named variables.
- Operators form the foundation of calculations and decisions in Java.
Summary
Operators are symbols that perform operations on values and variables. The values on which operators act are called operands, and combinations of operands and operators form expressions.
Arithmetic operators perform calculations such as addition, subtraction, multiplication, division, and remainder. Integer division discards the fractional part, while floating-point division preserves a fractional result within floating-point precision.
Unary operators work with one operand. Increment and decrement operators can appear in prefix or postfix form, and the position changes when the updated value becomes visible to the surrounding expression.
Assignment operators store and update values. Compound assignment combines an operation with assignment and includes an implicit conversion back to the type of the left-hand variable.
Relational operators compare values and produce boolean results. For reference types, == checks reference identity, while methods such as equals() are commonly used for content comparison.
Logical operators combine boolean expressions. The && and || operators use short-circuit evaluation, which can skip unnecessary expressions and help perform safe conditional checks.
Bitwise operators work directly with integer bits, while shift operators move bits left or right. These operators are useful in low-level data processing, flags, masks, and binary protocols.
The ternary operator selects one of two expressions based on a boolean condition. The instanceof operator checks reference type compatibility, and modern Java supports pattern matching that can create a typed variable during the check.
Operator precedence and associativity determine how complex expressions are grouped and evaluated. Parentheses should be used whenever they improve clarity or intentionally change the evaluation order.
Numeric promotion affects arithmetic expressions. Smaller integer types are commonly promoted to int, and calculations can overflow before being assigned to a wider variable if the operands are not promoted before the operation.
Understanding operators is essential because calculations, comparisons, assignments, conditions, loops, and nearly every meaningful Java program depend on expressions.
- You understand what an operator is.
- You understand operands and expressions.
- You know the major Java operator categories.
- You understand arithmetic operators.
- You understand addition.
- You understand subtraction.
- You understand multiplication.
- You understand division.
- You understand integer division.
- You understand floating-point division.
- You understand division by zero.
- You understand the modulus operator.
- You understand unary operators.
- You understand unary plus and minus.
- You understand increment and decrement.
- You understand prefix increment.
- You understand postfix increment.
- You can compare prefix and postfix behavior.
- You understand logical NOT.
- You understand bitwise complement.
- You understand assignment operators.
- You understand compound assignment.
- You understand implicit conversion in compound assignment.
- You understand relational operators.
- You understand equality and inequality operators.
- You understand primitive comparison.
- You understand reference comparison.
- You know how to compare String content.
- You understand logical operators.
- You understand logical AND.
- You understand logical OR.
- You understand short-circuit evaluation.
- You understand AND short-circuiting.
- You understand OR short-circuiting.
- You can compare && with &.
- You can compare || with |.
- You understand bitwise operators.
- You understand bitwise AND.
- You understand bitwise OR.
- You understand bitwise XOR.
- You understand binary representation.
- You understand shift operators.
- You understand left shift.
- You understand signed right shift.
- You understand unsigned right shift.
- You understand the ternary operator.
- You understand ternary syntax.
- You understand nested ternary expressions.
- You understand instanceof.
- You understand pattern matching with instanceof.
- You understand String concatenation.
- You understand String and number evaluation order.
- You understand operator precedence.
- You understand associativity.
- You understand the importance of parentheses.
- You can evaluate complex expressions.
- You understand numeric promotion.
- You understand mixed-type expressions.
- You understand overflow inside expressions.
- You can identify common operator errors.
- You know best practices for writing Java expressions.
- You are ready to learn Java input and output.