Operators

Introduction

Operators are special symbols that perform operations on variables and values. They are the building blocks for creating expressions and manipulating data in Java programs.

Categories of Operators

Java has several types of operators:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Relational (Comparison) Operators
  4. Logical Operators
  5. Unary Operators
  6. Bitwise Operators
  7. Ternary (Conditional) Operator
  8. instanceof Operator

1. Arithmetic Operators

Perform mathematical operations.

Operators:

OperatorNameDescriptionExample
+AdditionAdds two values5 + 3 = 8
-SubtractionSubtracts right from left5 - 3 = 2
*MultiplicationMultiplies two values5 * 3 = 15
/DivisionDivides left by right6 / 3 = 2
%ModulusReturns remainder5 % 3 = 2

Examples:

int a = 10, b = 3;

int sum = a + b;        // 13
int diff = a - b;       // 7
int product = a * b;    // 30
int quotient = a / b;   // 3 (integer division)
int remainder = a % b;  // 1

System.out.println(sum);       // 13
System.out.println(diff);      // 7
System.out.println(product);   // 30
System.out.println(quotient);  // 3
System.out.println(remainder); // 1

Special Cases:

1. Integer Division:

int result = 5 / 2;        // 2 (not 2.5)
double result = 5 / 2;     // 2.0 (still integer division)
double result = 5.0 / 2;   // 2.5 (correct)
double result = (double)5 / 2;  // 2.5 (correct)

2. Division by Zero:

int result = 10 / 0;       // ArithmeticException (runtime error)
double result = 10.0 / 0;  // Infinity (no error)
double result = 0.0 / 0;   // NaN (Not a Number)

3. Modulus with Negatives:

int r1 = 10 % 3;     // 1
int r2 = -10 % 3;    // -1
int r3 = 10 % -3;    // 1
int r4 = -10 % -3;   // -1
// Sign of result follows the dividend (left operand)

4. String Concatenation:

String s = "Hello" + " World";  // "Hello World"
String s = "Sum: " + 5 + 3;     // "Sum: 53" (not 8!)
String s = "Sum: " + (5 + 3);   // "Sum: 8"
int result = 5 + 3 + " is sum"; // Error: cannot convert String to int

2. Assignment Operators

Assign values to variables.

Basic Assignment:

int x = 10;  // Assigns 10 to x

Compound Assignment Operators:

OperatorExampleEquivalent To
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5

Examples:

int x = 10;

x += 5;   // x = x + 5;  → x = 15
x -= 3;   // x = x - 3;  → x = 12
x *= 2;   // x = x * 2;  → x = 24
x /= 4;   // x = x / 4;  → x = 6
x %= 4;   // x = x % 4;  → x = 2

Multiple Assignments:

int a, b, c;
a = b = c = 10;  // All get value 10
System.out.println(a);  // 10
System.out.println(b);  // 10
System.out.println(c);  // 10

3. Relational (Comparison) Operators

Compare two values and return boolean result (true/false).

Operators:

OperatorNameDescriptionExample
==Equal toChecks if equal5 == 5 → true
!=Not equal toChecks if not equal5 != 3 → true
>Greater thanLeft > Right5 > 3 → true
<Less thanLeft < Right3 < 5 → true
>=Greater than or equalLeft >= Right5 >= 5 → true
<=Less than or equalLeft <= Right3 <= 5 → true

Examples:

int a = 10, b = 5;

boolean result1 = (a == b);   // false
boolean result2 = (a != b);   // true
boolean result3 = (a > b);    // true
boolean result4 = (a < b);    // false
boolean result5 = (a >= 10);  // true
boolean result6 = (b <= 5);   // true

In Conditions:

int age = 18;

if (age >= 18) {
    System.out.println("Adult");
}

if (age == 18) {
    System.out.println("Just turned adult");
}

Important:

// For primitives
int a = 5, b = 5;
System.out.println(a == b);  // true (compares values)

// For objects (Strings)
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2);        // false (compares references)
System.out.println(s1.equals(s2));   // true (compares content)

4. Logical Operators

Combine multiple boolean expressions.

Operators:

| Operator | Name | Description | | -------- | ----------- | ------------------------- | ---------- | ---------------------------- | | && | Logical AND | True if both are true | | | | | Logical OR | True if at least one is true | | ! | Logical NOT | Inverts the boolean value |

Truth Tables:

AND (&&):

ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

OR (||): | A | B | A || B | |---|---|--------| | true | true | true | | true | false | true | | false | true | true | | false | false | false |

NOT (!):

A!A
truefalse
falsetrue

Examples:

boolean a = true, b = false;

// AND
boolean result1 = a && b;     // false
boolean result2 = true && true;   // true

// OR
boolean result3 = a || b;     // true
boolean result4 = false || false; // false

// NOT
boolean result5 = !a;         // false
boolean result6 = !b;         // true

In Conditions:

int age = 25;
boolean hasLicense = true;

// AND - Both must be true
if (age >= 18 && hasLicense) {
    System.out.println("Can drive");
}

// OR - At least one must be true
if (age < 18 || !hasLicense) {
    System.out.println("Cannot drive");
}

// Complex
int marks = 85;
if (marks >= 90 || (marks >= 80 && marks < 90)) {
    System.out.println("Grade: A");
}

Short-Circuit Evaluation:

// && stops if first is false
boolean result = false && (10 / 0 == 0);  // No error! Second part not evaluated

// || stops if first is true
boolean result = true || (10 / 0 == 0);   // No error! Second part not evaluated

5. Unary Operators

Operate on a single operand.

Operators:

OperatorNameDescriptionExample
+Unary plusPositive value+5
-Unary minusNegative value-5
++IncrementIncrease by 1++x or x++
--DecrementDecrease by 1--x or x--
!Logical NOTInverts boolean!true

Increment and Decrement:

Pre-increment (++x):

int x = 5;
int y = ++x;  // x is incremented first, then assigned
System.out.println(x);  // 6
System.out.println(y);  // 6

Post-increment (x++):

int x = 5;
int y = x++;  // x is assigned first, then incremented
System.out.println(x);  // 6
System.out.println(y);  // 5

Pre-decrement (—x):

int x = 5;
int y = --x;  // x is decremented first, then assigned
System.out.println(x);  // 4
System.out.println(y);  // 4

Post-decrement (x—):

int x = 5;
int y = x--;  // x is assigned first, then decremented
System.out.println(x);  // 4
System.out.println(y);  // 5

Summary:

int x = 5;
System.out.println(++x);  // 6 (increment first, then print)

int y = 5;
System.out.println(y++);  // 5 (print first, then increment)
System.out.println(y);    // 6 (now incremented)

In Loops:

// Both work the same in simple loops
for (int i = 0; i < 5; i++) {   // Post-increment
    System.out.println(i);
}

for (int i = 0; i < 5; ++i) {   // Pre-increment
    System.out.println(i);
}
// Output: 0 1 2 3 4 (same for both)

6. Bitwise Operators

Operate on individual bits of integer values.

Operators:

| Operator | Name | Description | | -------- | -------------------- | -------------------------- | ---------- | | & | AND | Bitwise AND | | | | OR | Bitwise OR | | ^ | XOR | Bitwise XOR | | ~ | NOT | Bitwise complement | | << | Left shift | Shift bits left | | >> | Right shift | Shift bits right | | >>> | Unsigned right shift | Shift right with zero fill |

Examples:

int a = 5;   // Binary: 0101
int b = 3;   // Binary: 0011

// Bitwise AND
int result1 = a & b;  // 0001 = 1

// Bitwise OR
int result2 = a | b;  // 0111 = 7

// Bitwise XOR
int result3 = a ^ b;  // 0110 = 6

// Bitwise NOT
int result4 = ~a;     // Inverts all bits

// Left Shift
int result5 = a << 1; // 1010 = 10 (multiply by 2)

// Right Shift
int result6 = a >> 1; // 0010 = 2 (divide by 2)

Practical Use:

// Check if number is even
boolean isEven = (num & 1) == 0;  // Last bit is 0 for even

// Multiply by 2
int doubled = num << 1;

// Divide by 2
int halved = num >> 1;

7. Ternary (Conditional) Operator

Shorthand for if-else statement.

Syntax:

variable = (condition) ? value_if_true : value_if_false;

Examples:

// Basic usage
int a = 10, b = 5;
int max = (a > b) ? a : b;
System.out.println(max);  // 10

// Instead of:
int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

More Examples:

// Check even/odd
int num = 7;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(result);  // "Odd"

// Age category
int age = 25;
String category = (age >= 18) ? "Adult" : "Minor";
System.out.println(category);  // "Adult"

// Nested ternary
int marks = 85;
String grade = (marks >= 90) ? "A" :
               (marks >= 80) ? "B" :
               (marks >= 70) ? "C" : "F";
System.out.println(grade);  // "B"

8. instanceof Operator

Checks if an object is an instance of a specific class or interface.

Syntax:

object instanceof ClassName

Examples:

String str = "Hello";
boolean result = str instanceof String;  // true

Integer num = 10;
boolean result = num instanceof Integer; // true
boolean result = num instanceof Number;  // true (Integer extends Number)

Object obj = "Test";
boolean result = obj instanceof String;  // true

Operator Precedence

Order in which operators are evaluated:

| Precedence | Operator | Description | | ----------- | --------------------- | -------------- | ---------- | ---------- | | 1 (Highest) | () | Parentheses | | 2 | ++, --, !, ~ | Unary | | 3 | *, /, % | Multiplicative | | 4 | +, - | Additive | | 5 | <<, >>, >>> | Shift | | 6 | <, <=, >, >= | Relational | | 7 | ==, != | Equality | | 8 | & | Bitwise AND | | 9 | ^ | Bitwise XOR | | 10 | | | Bitwise OR | | 11 | && | Logical AND | | 12 | | | | Logical OR | | 13 | ?: | Ternary | | 14 (Lowest) | =, +=, -=, etc. | Assignment |

Examples:

// Without parentheses
int result = 5 + 3 * 2;      // 11 (not 16)
// Multiplication has higher precedence

// With parentheses
int result = (5 + 3) * 2;    // 16

// Complex
int result = 10 + 5 * 2 / 5 - 2;  // 10
// Order: 5*2=10, 10/5=2, 10+2=12, 12-2=10

// Use parentheses for clarity
int result = 10 + ((5 * 2) / 5) - 2;  // Same, but clearer

Common Mistakes

1. Assignment vs Comparison:

int x = 10;
if (x = 5) {  // ❌ Error: incompatible types
    // Should be: if (x == 5)
}

2. Integer Division:

double result = 5 / 2;     // 2.0 (not 2.5)
double result = 5.0 / 2;   // 2.5 ✓

3. Post vs Pre Increment:

int x = 5;
int y = x++;  // y = 5, x = 6

int a = 5;
int b = ++a;  // b = 6, a = 6

4. String Concatenation Order:

System.out.println("Sum: " + 5 + 3);    // "Sum: 53"
System.out.println("Sum: " + (5 + 3)); // "Sum: 8" ✓
System.out.println(5 + 3 + " is sum"); // "8 is sum" ✓

5. Logical Operators with Non-Boolean:

int x = 5;
if (x) {  // ❌ Error: incompatible types
    // Should be: if (x > 0) or if (x != 0)
}

Exam Tips

Remember:

  1. Arithmetic: +, -, *, /, %
  2. Assignment: =, +=, -=, *=, /=, %=
  3. Relational: ==, !=, >, <, >=, <=
  4. Logical: &&, ||, !
  5. Unary: ++, --, +, -, !
  6. Ternary: condition ? true_value : false_value

Key Points:

  1. Integer division: 5 / 2 = 2 (not 2.5)
  2. Modulus sign: Follows dividend
  3. Post-increment: x++ - use then increment
  4. Pre-increment: ++x - increment then use
  5. Short-circuit: && and || stop early if possible
  6. String concatenation: + with String
  7. Precedence: * / before + -
  8. Parentheses: Use for clarity

Common Questions:

  1. What is the difference between ++x and x++?
  2. Explain short-circuit evaluation
  3. What is the output of 5 / 2 in Java?
  4. Difference between == and equals()
  5. Operator precedence order
  6. What is ternary operator?
  7. Explain compound assignment operators