Operators
java operators arithmetic assignment relational logical ternary bitwise shift precedence increment decrement equals comparison
Introduction
Almost every Java program performs operations on data.
A banking application calculates account balances.
An e-commerce website calculates discounts.
A school management system compares student marks.
A login system verifies usernames and passwords.
A game updates scores and player positions.
These operations are performed using operators.
An operator is a symbol that tells Java to perform a specific operation on one or more values (called operands).
Example:
int total = 10 + 20;
Here:
10and20are operands+is the operator
Operators are one of the most frequently used features in Java and are essential for writing logical, mathematical, and business-related programs.
In this lesson, you'll learn:
- Arithmetic Operators
- Assignment Operators
- Comparison (Relational) Operators
- Logical Operators
- Unary Operators
- Increment & Decrement Operators
- Ternary Operator
- Bitwise Operators
- Shift Operators
- Operator Precedence
- Real-world examples
- Best Practices
- Common Mistakes
- Hands-on Exercises
- Professional Interview Questions
Types of Operators
Java provides several categories of operators.
Java Operators├── Arithmetic├── Assignment├── Relational├── Logical├── Unary├── Increment & Decrement├── Ternary├── Bitwise└── Shift
Let's explore each category.
Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 5 + 3 |
- | Subtraction | 5 - 3 |
* | Multiplication | 5 * 3 |
/ | Division | 10 / 2 |
% | Modulus (Remainder) | 10 % 3 |
Example:
int a = 20;int b = 6;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);
Output:
261412032
Real-World Example: Shopping Total
An online shopping application calculates the total price.
double price = 1200.00;double tax = 216.00;double total = price + tax;System.out.println(total);
Output:
1416.0
Assignment Operators
Assignment operators assign values to variables.
Basic assignment:
int age = 25;
Compound assignment operators:
| Operator | Example | Equivalent |
|---|---|---|
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
%= | x %= 5 | x = x % 5 |
Example:
int score = 80;score += 10;System.out.println(score);
Output:
90
Relational (Comparison) Operators
These operators compare values and always return a boolean.
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
Example:
int age = 18;System.out.println(age >= 18);
Output:
true
Real-World Example: Voting Eligibility
Determine voting eligibility.
int age = 20;boolean canVote = age >= 18;System.out.println(canVote);
Output:
true
Logical Operators
Logical operators combine multiple conditions.
| Operator | Meaning |
|---|---|
&& | Logical AND |
|| | Logical OR |
! | Logical NOT |
Logical AND (`&&`)
Both conditions must be true.
int age = 25;boolean citizen = true;System.out.println(age >= 18 && citizen);
Output:
true
Logical OR (`||`)
Only one condition must be true.
boolean weekend = false;boolean holiday = true;System.out.println(weekend || holiday);
Output:
true
Logical NOT (`!`)
Reverses a boolean value.
boolean loggedIn = false;System.out.println(!loggedIn);
Output:
true
Unary Operators
Unary operators work with a single operand.
| Operator | Meaning |
|---|---|
+ | Unary plus |
- | Unary minus |
! | Logical NOT |
++ | Increment |
-- | Decrement |
Example:
int number = 10;System.out.println(-number);
Output:
-10
Increment Operator (`++`)
Increases a value by one.
int count = 5;count++;System.out.println(count);
Output:
6
Decrement Operator (`--`)
Decreases a value by one.
int count = 5;count--;System.out.println(count);
Output:
4
Prefix vs Postfix
Prefix:
int x = 5;System.out.println(++x);
Output:
6
Postfix:
int x = 5;System.out.println(x++);System.out.println(x);
Output:
56
Rule:
- Prefix updates the value before it is used.
- Postfix uses the current value first, then updates it.
Ternary Operator
The ternary operator is a compact alternative to a simple if-else statement.
Syntax:
condition ? valueIfTrue : valueIfFalse
Example:
int age = 20;String result = age >= 18 ? "Adult" : "Minor";System.out.println(result);
Output:
Adult
Bitwise Operators
Bitwise operators work directly with the binary representation of integers.
| Operator | Meaning |
|---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
~ | Bitwise Complement |
Example:
int a = 5;int b = 3;System.out.println(a & b);
These operators are commonly used in low-level programming, networking, cryptography, and performance-sensitive applications.
Shift Operators
Shift operators move bits left or right.
| Operator | Meaning |
|---|---|
<< | Left Shift |
>> | Signed Right Shift |
>>> | Unsigned Right Shift |
Example:
int value = 8;System.out.println(value << 1);
Output:
16
Shifting left by one position is generally equivalent to multiplying by two for positive integers.
Operator Precedence
Java evaluates expressions according to operator precedence.
Example:
int result = 10 + 5 * 2;
Output:
20
Multiplication is performed before addition.
Use parentheses to make expressions clear.
int result = (10 + 5) * 2;
Output:
30
Real-World Example: Premium Discount
An online shopping application applies a discount only if the customer is a premium member and the order value exceeds ₹5,000.
double orderAmount = 6500;boolean premiumMember = true;boolean eligibleForDiscount =orderAmount > 5000 && premiumMember;System.out.println(eligibleForDiscount);
Output:
true
Best Practices
Use Parentheses for Clarity
Even if operator precedence makes an expression valid, parentheses improve readability.
Example:
double total = (price + tax) - discount;
Prefer Readability
Avoid writing overly complex expressions in a single line.
Break them into smaller steps if needed.
Use Compound Assignment Carefully
+= and similar operators improve readability for simple updates.
Avoid chaining assignments when it makes the code confusing.
Avoid Magic Numbers
Instead of:
salary = salary * 12;
Use descriptive constants where appropriate.
Compare Objects Correctly
For primitive values, use ==.
For many objects such as String, compare contents using methods like .equals() instead of ==. You'll learn this in the Strings lesson.
Common Mistakes
Using = Instead of ==
Incorrect:
if (age = 18)
Correct:
if (age == 18)
= assigns a value.
== compares values.
Integer Division
System.out.println(5 / 2);
Output:
2
Because both operands are integers, the fractional part is discarded.
Use a floating-point operand if you need a decimal result.
Confusing Prefix and Postfix
x++;
is not the same as
++x;
Understand when the increment happens.
Ignoring Operator Precedence
Always use parentheses if there's any possibility of confusion.
Comparing Strings with ==
== checks whether two references point to the same object, not whether two strings contain the same text.
Use .equals() for content comparison.
Hands-on Exercise
Create a Java program that:
- Calculates the total bill using arithmetic operators.
- Updates a score using assignment operators.
- Checks whether a student passed using relational operators.
- Determines eligibility for a scholarship using logical operators.
- Demonstrates prefix and postfix increment.
- Uses the ternary operator to display "Pass" or "Fail".
- Uses a left shift operator on an integer and explains the result.
- Uses parentheses to change the outcome of an arithmetic expression.
Try predicting the output before running each example.
Summary
Operators are the building blocks of Java expressions.
They allow you to perform calculations, compare values, evaluate conditions, manipulate bits, and control program logic.
Understanding how operators work—and especially how precedence and data types affect expressions—will help you write correct, readable, and efficient Java programs.
Key Takeaways
- Operators perform operations on one or more operands.
- Java provides arithmetic, assignment, relational, logical, unary, ternary, bitwise, and shift operators.
- Comparison operators return
booleanvalues. - Prefix and postfix increment behave differently.
- Use parentheses to improve readability and avoid precedence-related bugs.
- Integer division discards the fractional part.
- Use
==for primitive comparisons and appropriate methods such as.equals()for comparing object contents.
Professional Interview Questions
1What is the difference between = and == in Java?
Professional Answer
The = operator assigns a value to a variable, whereas the == operator compares two values. For primitive types, == compares actual values. For object references, == checks whether both references point to the same object.
Follow-up Questions
- How do you compare two String objects?
- Why does == behave differently for primitives and objects?
Interview Tip: Clearly distinguish assignment from comparison, then explain the difference between primitive values and object references.
2What is the difference between prefix (++x) and postfix (x++) increment?
Professional Answer
With prefix increment (++x), the variable is incremented before its value is used. With postfix increment (x++), the current value is used first, and the increment happens afterward.
Follow-up Questions
- What will System.out.println(x++) print if x is 5?
- When would prefix increment be preferable?
Interview Tip: Walk through a simple example step by step instead of only giving the definition.
3Why does 5 / 2 return 2 instead of 2.5?
Professional Answer
Both operands are integers, so Java performs integer division, which discards the fractional part. To obtain a decimal result, at least one operand must be a floating-point type, for example 5.0 / 2.
Follow-up Questions
- What is the result of 5.0 / 2?
- How does Java choose the result type in arithmetic expressions?
Interview Tip: Mention that Java performs automatic numeric promotion during arithmetic operations, but the operand types determine the kind of division performed.