LearnContact
Lesson 1055 min read

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.

Operator Examples
int first = 10;
int second = 5;

int sum = first + second;

boolean greater = first > second;

boolean valid = first > 0 && second > 0;

first++;
Operator Concept
VALUE

   │
   ▼

OPERATOR

   │
   ▼

OPERATION

   │
   ▼

RESULT
What You Will Learn
  • 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.

Simple Operation
int result = 10 + 5;
Expression Structure
10 + 5
│  │  │
│  │  └── Operand
│  │
│  └───── Operator
│
└──────── Operand

In 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.

Calculator Analogy
10        +        5

INPUT   OPERATION   INPUT

          │
          ▼

         15

        RESULT

Operands 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.

Expression Examples
int result = 10 + 5;

int total = result * 2;

boolean valid = total > 20;
Expression Evaluation
10 + 5

   │
   ▼

15


15 * 2

   │
   ▼

30


30 > 20

   │
   ▼

true

Operator Categories

Java Operator Categories
JAVA OPERATORS

├── Arithmetic Operators
├── Unary Operators
├── Assignment Operators
├── Relational Operators
├── Logical Operators
├── Bitwise Operators
├── Shift Operators
├── Ternary Operator
└── instanceof Operator

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numeric values.

Arithmetic Operators
OPERATOR    OPERATION

+           Addition

-           Subtraction

*           Multiplication

/           Division

%           Remainder
Arithmetic Example
int 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.

Addition
int first = 10;
int second = 5;

int result = first + second;

System.out.println(result);
Output
15

Subtraction Operator

The - operator subtracts the right operand from the left operand.

Subtraction
int first = 10;
int second = 5;

int result = first - second;

System.out.println(result);
Output
5

Multiplication Operator

The * operator multiplies two numeric operands.

Multiplication
int quantity = 5;
int price = 100;

int total = quantity * price;

System.out.println(total);
Output
500

Division Operator

The / operator divides the left operand by the right operand. The result depends on the operand types.

Division
int result = 10 / 2;

System.out.println(result);
Output
5

Integer Division

When both operands are integer types, Java performs integer division. The fractional part is discarded.

Integer Division
int result = 10 / 3;

System.out.println(result);
Output
3
Evaluation
10 / 3

Mathematical Result:
3.333...

Integer Division Result:
3
Fractional Part is Discarded
  • 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.

Floating-Point Division
double first = 10.0;
int second = 3;

double result = first / second;

System.out.println(result);
Output
3.3333333333333335
Force Decimal Division
double 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.

Integer Division by Zero
int number = 10;
int zero = 0;

// int result = number / zero;
// ArithmeticException
Floating-Point Division by Zero
double 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);
Output
Infinity
-Infinity
NaN
Important Difference
  • 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.

Modulus
int result = 10 % 3;

System.out.println(result);
Evaluation
10 ÷ 3

Quotient  = 3

Remainder = 1

10 % 3 = 1
Even or Odd
int number = 10;

boolean even = number % 2 == 0;

System.out.println(even);

Arithmetic Examples

Complete Arithmetic Example
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));
Output
Addition: 26
Subtraction: 14
Multiplication: 120
Division: 3
Remainder: 2

Unary Operators

Unary operators operate on a single operand.

Unary Operators
OPERATOR    PURPOSE

+           Unary plus

-           Unary minus

++          Increment

--          Decrement

!           Logical NOT

~           Bitwise complement

Unary Plus

The unary + operator indicates a positive numeric value.

Unary Plus
int number = 10;

int result = +number;

System.out.println(result);
Output
10

Unary Minus

The unary - operator negates a numeric value.

Unary Minus
int number = 10;

int result = -number;

System.out.println(result);
Output
-10

Increment Operator

The ++ operator increases a variable by 1.

Increment
int count = 10;

count++;

System.out.println(count);
Output
11

Decrement Operator

The -- operator decreases a variable by 1.

Decrement
int count = 10;

count--;

System.out.println(count);
Output
9

Prefix Increment

With prefix increment, the variable is incremented before its value is used in the surrounding expression.

Prefix Increment
int number = 5;

int result = ++number;

System.out.println(number);
System.out.println(result);
Evaluation
number = 5

++number

1. Increment number to 6
2. Use value 6

result = 6

Postfix Increment

With postfix increment, the current value is used first and the variable is incremented afterward.

Postfix Increment
int number = 5;

int result = number++;

System.out.println(number);
System.out.println(result);
Evaluation
number = 5

number++

1. Use value 5
2. Increment number to 6

result = 5

Prefix vs Postfix

Comparison
PREFIX

int x = 5;
int y = ++x;

x = 6
y = 6


POSTFIX

int x = 5;
int y = x++;

x = 6
y = 5
Keep Increment Expressions Simple
  • 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.

Logical NOT
boolean active = true;

boolean inactive = !active;

System.out.println(inactive);
Truth Table
VALUE     !VALUE

true      false

false     true

Bitwise Complement

The ~ operator flips every bit of an integer value.

Bitwise Complement
int number = 5;

int result = ~number;

System.out.println(result);
Output
-6

For integer values, the result follows the two’s-complement relationship ~x equals -(x + 1).

Assignment Operators

Assignment operators store or update values in variables.

Assignment Operators
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 >>>= 1

Simple Assignment

Assignment
int number;

number = 10;

System.out.println(number);
Assignment Direction
number = 10;

   ◄──────

Value on the right

is assigned to

variable on the left

Compound Assignment

Compound assignment combines an operation with assignment.

Compound Assignment
int number = 10;

number += 5;

System.out.println(number);
Equivalent Concept
number += 5;

Similar purpose:

number = number + 5;

Addition Assignment

Addition Assignment
int score = 100;

score += 50;

System.out.println(score);
Output
150

Subtraction Assignment

Subtraction Assignment
int balance = 1000;

balance -= 200;

System.out.println(balance);
Output
800

Multiplication Assignment

Multiplication Assignment
int number = 5;

number *= 4;

System.out.println(number);
Output
20

Division Assignment

Division Assignment
int number = 20;

number /= 4;

System.out.println(number);
Output
5

Modulus Assignment

Modulus Assignment
int number = 10;

number %= 3;

System.out.println(number);
Output
1

Compound Assignment and Implicit Conversion

Compound assignment includes an implicit conversion back to the type of the left-hand variable.

Compound Assignment
byte value = 10;

value += 5;

System.out.println(value);
Normal Addition
byte value = 10;

// value = value + 5;
// Compilation error

value = (byte) (value + 5);
Compound Assignment is Not Always Identical to Expanded Form
  • 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.

Relational Operators
OPERATOR    MEANING

==          Equal to

!=          Not equal to

>           Greater than

<           Less than

>=          Greater than or equal to

<=          Less than or equal to

Equal To Operator

Equal To
int first = 10;
int second = 10;

boolean result = first == second;

System.out.println(result);
Output
true

Not Equal To Operator

Not Equal To
int first = 10;
int second = 5;

boolean result = first != second;

System.out.println(result);
Output
true

Greater Than Operator

Greater Than
int age = 25;

boolean result = age > 18;

System.out.println(result);

Less Than Operator

Less Than
int temperature = 10;

boolean cold = temperature < 15;

System.out.println(cold);

Greater Than or Equal To Operator

Greater Than or Equal To
int age = 18;

boolean eligible = age >= 18;

System.out.println(eligible);

Less Than or Equal To Operator

Less Than or Equal To
int score = 40;

boolean failed = score <= 40;

System.out.println(failed);

Comparing Primitive Values

For compatible primitive values, comparison operators compare the represented values.

Primitive Comparison
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.

Reference Comparison
String first = new String("Java");

String second = new String("Java");

System.out.println(first == second);
Output
false
Reference Model
first ─────► "Java" Object 1

second ────► "Java" Object 2

Different Objects

first == second

false

Comparing Strings

Use equals() when you want to compare String content.

Correct String Comparison
String first = new String("Java");

String second = new String("Java");

System.out.println(first.equals(second));
Output
true
== vs equals()
  • == 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.

Logical Operators
OPERATOR    MEANING

&&          Logical AND

||          Logical OR

!           Logical NOT

Logical AND

The && operator produces true only when both operands are true.

AND Truth Table
A        B        A && B

false    false    false

false    true     false

true     false    false

true     true     true
Logical AND
int 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.

OR Truth Table
A        B        A || B

false    false    false

false    true     true

true     false    true

true     true     true
Logical OR
boolean admin = false;
boolean owner = true;

boolean allowed =
        admin || owner;

System.out.println(allowed);

Logical NOT Operator

Logical NOT
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.

Short-Circuit Concept
false && anything

Result already known:
false

Right side skipped


true || anything

Result already known:
true

Right side skipped

AND Short-Circuit

Safe Null Check
String name = null;

boolean valid =
        name != null
        && name.length() > 3;

System.out.println(valid);
Evaluation
name != null

false

        │
        ▼

Second condition skipped

        │
        ▼

false

OR Short-Circuit

OR 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 Evaluation
boolean first = false;
boolean second = true;

System.out.println(first & second);
System.out.println(first | second);
&& vs & and || vs |
  • && 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.

Bitwise Operators
OPERATOR    OPERATION

&           Bitwise AND

|           Bitwise OR

^           Bitwise XOR

~           Bitwise complement

Bitwise AND

Bitwise AND
5 = 0101

3 = 0011

    0101
&   0011
────────
    0001

Result = 1
Bitwise AND Example
int result = 5 & 3;

System.out.println(result);

Bitwise OR

Bitwise OR
5 = 0101

3 = 0011

    0101
|   0011
────────
    0111

Result = 7
Bitwise OR Example
int result = 5 | 3;

System.out.println(result);

Bitwise XOR

The ^ operator produces 1 for each bit position where the corresponding operand bits are different.

Bitwise XOR
5 = 0101

3 = 0011

    0101
^   0011
────────
    0110

Result = 6
Bitwise XOR Example
int result = 5 ^ 3;

System.out.println(result);

Bitwise Complement Operator

Complement
int number = 5;

int result = ~number;

System.out.println(result);
Relationship
~x = -(x + 1)

~5

= -(5 + 1)

= -6

Binary Representation

Bitwise operations become easier to understand when values are written in binary.

Binary Output
int number = 10;

String binary =
        Integer.toBinaryString(number);

System.out.println(binary);
Output
1010

Shift Operators

Shift operators move the bits of an integer value left or right.

Shift Operators
OPERATOR    MEANING

<<          Left shift

>>          Signed right shift

>>>         Unsigned right shift

Left Shift

The << operator shifts bits to the left and fills the new low-order positions with zeros.

Left Shift
int number = 5;

int result = number << 1;

System.out.println(result);
Binary View
5

0101

Shift left by 1

1010

10

Signed Right Shift

The >> operator shifts bits to the right while preserving the sign through sign extension.

Signed Right Shift
int number = 20;

int result = number >> 2;

System.out.println(result);
Output
5

Unsigned Right Shift

The >>> operator shifts bits to the right and fills the new high-order positions with zeros.

Unsigned Right Shift
int number = -8;

int result = number >>> 1;

System.out.println(result);
>> vs >>>
  • >> 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

Shift Operations
int number = 16;

System.out.println(number << 1);
System.out.println(number >> 1);
System.out.println(number >>> 1);
Output
32
8
8

Ternary Operator

The conditional operator, commonly called the ternary operator, selects one of two expressions based on a boolean condition.

Ternary Structure
condition ? valueIfTrue : valueIfFalse

Ternary Syntax

Ternary Syntax
int age = 20;

String result =
        age >= 18
        ? "Adult"
        : "Minor";

System.out.println(result);
Evaluation
age >= 18

     │
     ▼

   true

     │
     ▼

"Adult"

Ternary Examples

Maximum Value
int a = 10;
int b = 20;

int maximum =
        a > b ? a : b;

System.out.println(maximum);
Even or Odd
int number = 7;

String result =
        number % 2 == 0
        ? "Even"
        : "Odd";

System.out.println(result);

Nested Ternary Operator

Nested Ternary
int number = 0;

String result =
        number > 0
        ? "Positive"
        : number < 0
            ? "Negative"
            : "Zero";

System.out.println(result);
Avoid Complex Nested Ternary Expressions
  • 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.

instanceof Example
Object value = "Java";

boolean result =
        value instanceof String;

System.out.println(result);
Output
true
null instanceof
Object value = null;

System.out.println(
        value instanceof String
);
Output
false

Pattern Matching with instanceof

Modern Java allows instanceof to test a type and create a pattern variable in one operation.

Pattern Matching
Object value = "Java Programming";

if (value instanceof String text) {

    System.out.println(text.length());

}
Concept
OLD STYLE

Check type

        │
        ▼

Cast manually

        │
        ▼

Use value


PATTERN MATCHING

Check type

        │
        ▼

Create typed variable

        │
        ▼

Use value

String Concatenation

When one operand of + is a String, Java performs String concatenation.

String Concatenation
String firstName = "Alex";
String lastName = "Smith";

String fullName =
        firstName + " " + lastName;

System.out.println(fullName);
Output
Alex Smith

String and Number Evaluation

The + operator is evaluated from left to right, so the position of a String can change the result.

Evaluation Order
System.out.println(10 + 20 + " Java");

System.out.println("Java " + 10 + 20);
Output
30 Java

Java 1020
Evaluation
10 + 20 + " Java"

30 + " Java"

"30 Java"


"Java " + 10 + 20

"Java 10" + 20

"Java 1020"
Use Parentheses
System.out.println(
        "Java " + (10 + 20)
);
Output
Java 30

Operator Precedence

Operator precedence determines which operator is evaluated first when an expression contains multiple operators.

Precedence Example
int result = 10 + 5 * 2;

System.out.println(result);
Evaluation
10 + 5 * 2

Multiplication first:

5 * 2 = 10

Then addition:

10 + 10 = 20
Simplified Precedence Order
HIGHER PRECEDENCE

()
Postfix ++ --
Unary ++ -- + - ! ~
* / %
+ -
<< >> >>>
< <= > >= instanceof
== !=
&
^
|
&&
||
? :
Assignment

LOWER PRECEDENCE

Associativity

Associativity determines evaluation grouping when operators have the same precedence.

Left Associativity
int result = 20 - 5 - 3;

System.out.println(result);
Evaluation
20 - 5 - 3

        │
        ▼

(20 - 5) - 3

        │
        ▼

15 - 3

        │
        ▼

12
Right Associative Assignment
int a;
int b;
int c;

a = b = c = 10;
Assignment Evaluation
a = b = c = 10

        │
        ▼

c = 10

        │
        ▼

b = 10

        │
        ▼

a = 10

Using Parentheses

Parentheses can change evaluation order and make complex expressions easier to understand.

Without Parentheses
int result = 10 + 5 * 2;

System.out.println(result);
Output
20
With Parentheses
int result = (10 + 5) * 2;

System.out.println(result);
Output
30
Prefer Clarity
  • 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

Complex Expression
int result =
        10 + 5 * 2 - 4 / 2;

System.out.println(result);
Step-by-Step Evaluation
10 + 5 * 2 - 4 / 2

        │
        ▼

10 + 10 - 2

        │
        ▼

20 - 2

        │
        ▼

18

Numeric Promotion

Java promotes smaller integer types during arithmetic expressions.

Integer Promotion
byte first = 10;
byte second = 20;

// byte result = first + second;
// Compilation error

int result = first + second;
Promotion
byte + byte

     │
     ▼

int + int

     │
     ▼

int result
Binary Numeric Promotion
  • 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

Mixed Types
int number = 10;

double price = 2.5;

double result = number * price;

System.out.println(result);
Promotion
int

10

   │
   ▼

Promoted to double

10.0

   │
   ▼

10.0 * 2.5

   │
   ▼

25.0

Overflow in Expressions

The type of the final variable does not automatically change the type used for an earlier arithmetic operation.

Overflow Before Assignment
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.

Correct Promotion
int first = 1_000_000;
int second = 1_000_000;

long result =
        (long) first * second;

System.out.println(result);
Correct Result
1000000000000
Promote Before the Operation
  • 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

Common 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 Order
Wrong String Comparison
String 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));
Integer Division Mistake
double result = 10 / 3;

System.out.println(result);

// Output:
// 3.0
Correct Decimal Division
double 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

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 intent

Common Misconceptions

Avoid These 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

Exercise 1: Arithmetic Calculator
  • Create two integer variables.
  • Calculate their sum.
  • Calculate their difference.
  • Calculate their product.
  • Calculate their quotient.
  • Calculate their remainder.
  • Print every result.
Exercise 2: Integer vs Decimal Division
  • 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.
Exercise 3: Even or Odd
  • Create an integer variable.
  • Use the modulus operator.
  • Create a boolean expression that checks whether the number is even.
  • Print the result.
Exercise 4: Prefix and Postfix
  • 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.
Exercise 5: Compound Assignment
  • Create a score variable.
  • Increase it using +=.
  • Decrease it using -=.
  • Multiply it using *=.
  • Divide it using /=.
  • Print the result after each operation.
Exercise 6: Relational Operators
  • 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.
Exercise 7: Logical Operators
  • 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.
Exercise 8: Short-Circuit Evaluation
  • 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.
Exercise 9: Bitwise Operators
  • Create values 5 and 3.
  • Apply bitwise AND.
  • Apply bitwise OR.
  • Apply bitwise XOR.
  • Print each result in decimal.
  • Print each result in binary.
Exercise 10: Ternary Operator
  • 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.
Exercise 11: Operator Precedence
  • Evaluate 10 + 5 * 2.
  • Evaluate (10 + 5) * 2.
  • Print both results.
  • Explain why the outputs are different.
Exercise 12: Overflow Prevention
  • 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.

Lesson 10 Completed
  • 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.
Next Lesson →

Input & Output in Java