Course Content

Mastering Operators in Java: The Tools of Computation

Introduction

Operators are the workhorses of Java programming—the symbols that enable us to perform operations on variables and values. From basic arithmetic to complex logical decisions, operators give Java its computational power. This comprehensive guide will explore all categories of Java operators, providing practical examples and insights that will enhance your programming skills.

What Are Operators?

In simplest terms, operators are special symbols that perform specific operations on one, two, or three operands (values/variables) and return a result. Think of them as the verbs in the language of Java—they "do things" to data.

1. Arithmetic Operators: The Mathematical Foundation

Arithmetic operators are used to perform basic mathematical operations.

Basic Arithmetic Operators

java
public class ArithmeticDemo {
    public static void main(String[] args) {
        int a = 15, b = 4;
        
        System.out.println("Addition: " + (a + b));      // 19
        System.out.println("Subtraction: " + (a - b));   // 11
        System.out.println("Multiplication: " + (a * b)); // 60
        System.out.println("Division: " + (a / b));      // 3 (integer division)
        System.out.println("Modulus: " + (a % b));       // 3 (remainder)
        
        // For precise division
        double result = (double) a / b;  // 3.75
        System.out.println("Precise division: " + result);
    }
}

Special Arithmetic Cases

java
// Division nuances
System.out.println(10 / 3);     // 3 (integer division)
System.out.println(10.0 / 3);   // 3.3333333333333335
System.out.println(10 / 3.0);   // 3.3333333333333335

// Modulus with negative numbers
System.out.println(10 % 3);     // 1
System.out.println(-10 % 3);    // -1
System.out.println(10 % -3);    // 1
System.out.println(-10 % -3);   // -1

2. Assignment Operators: Storing Values

Assignment operators are used to assign values to variables.

Basic and Compound Assignment

java
int x = 10;          // Simple assignment
x += 5;             // Equivalent to x = x + 5 (now x = 15)
x -= 3;             // Equivalent to x = x - 3 (now x = 12)
x *= 2;             // Equivalent to x = x * 2 (now x = 24)
x /= 4;             // Equivalent to x = x / 4 (now x = 6)
x %= 4;             // Equivalent to x = x % 4 (now x = 2)

// Multiple assignment
int a, b, c;
a = b = c = 100;    // All variables get value 100

3. Relational/Comparison Operators: Making Comparisons

These operators compare two values and return a boolean result (true or false).

java
public class ComparisonDemo {
    public static void main(String[] args) {
        int x = 10, y = 20, z = 10;
        
        System.out.println("x == y: " + (x == y));  // false
        System.out.println("x == z: " + (x == z));  // true
        System.out.println("x != y: " + (x != y));  // true
        System.out.println("x < y: " + (x < y));    // true
        System.out.println("x > y: " + (x > y));    // false
        System.out.println("x <= z: " + (x <= z));  // true
        System.out.println("y >= z: " + (y >= z));  // true
        
        // Comparing objects (use .equals() for content comparison)
        String s1 = "hello";
        String s2 = "hello";
        String s3 = new String("hello");
        
        System.out.println(s1 == s2);      // true (same string pool reference)
        System.out.println(s1 == s3);      // false (different objects)
        System.out.println(s1.equals(s3)); // true (same content)
    }
}

4. Logical Operators: Decision Making

Logical operators are used to combine multiple boolean expressions.

Basic Logical Operators

java
public class LogicalDemo {
    public static void main(String[] args) {
        boolean a = true, b = false;
        
        System.out.println("a && b: " + (a && b));   // false (AND)
        System.out.println("a || b: " + (a || b));   // true (OR)
        System.out.println("!a: " + (!a));           // false (NOT)
        
        // Practical example
        int age = 25;
        boolean hasLicense = true;
        
        if (age >= 18 && hasLicense) {
            System.out.println("Can drive legally");
        }
        
        // Short-circuit evaluation
        int value = 10;
        if (value != 0 && (100 / value) > 5) {
            // Won't cause division by zero error due to short-circuit
            System.out.println("Condition satisfied");
        }
    }
}

Truth Tables for Logical Operators

 
 
A B A && B A || B !A
true true true true false
true false false true false
false true false true true
false false false false true

5. Bitwise Operators: Working with Bits

Bitwise operators perform operations on individual bits of integer types.

java
public class BitwiseDemo {
    public static void main(String[] args) {
        int a = 5;    // Binary: 0101
        int b = 3;    // Binary: 0011
        
        System.out.println("a & b: " + (a & b));   // 1 (0101 & 0011 = 0001)
        System.out.println("a | b: " + (a | b));   // 7 (0101 | 0011 = 0111)
        System.out.println("a ^ b: " + (a ^ b));   // 6 (0101 ^ 0011 = 0110)
        System.out.println("~a: " + (~a));         // -6 (invert all bits)
        
        // Shift operators
        int x = 8;    // Binary: 1000
        System.out.println("x << 1: " + (x << 1)); // 16 (left shift: 10000)
        System.out.println("x >> 1: " + (x >> 1)); // 4 (right shift: 0100)
        System.out.println("x >>> 1: " + (x >>> 1)); // 4 (unsigned right shift)
    }
}

Practical Bitwise Applications

java
// Checking if a number is even or odd
int number = 13;
if ((number & 1) == 0) {
    System.out.println("Even");
} else {
    System.out.println("Odd");
}

// Fast multiplication/division by powers of 2
int value = 10;
System.out.println(value << 1);  // 20 (multiply by 2)
System.out.println(value << 2);  // 40 (multiply by 4)
System.out.println(value >> 1);  // 5 (divide by 2)

6. Unary Operators: Single Operand Operations

Unary operators require only one operand.

java
public class UnaryDemo {
    public static void main(String[] args) {
        int x = 10;
        
        // Increment/Decrement
        System.out.println("Original x: " + x);      // 10
        System.out.println("Post-increment: " + x++); // 10 (then x becomes 11)
        System.out.println("After: " + x);           // 11
        System.out.println("Pre-increment: " + ++x); // 12
        System.out.println("Post-decrement: " + x--); // 12 (then x becomes 11)
        System.out.println("Pre-decrement: " + --x); // 10
        
        // Unary plus and minus
        int positive = +5;    // Explicitly positive (rarely used)
        int negative = -5;    // Negation
        System.out.println("Negative of 5: " + negative);
        
        // Logical complement
        boolean flag = true;
        System.out.println("!flag: " + !flag);  // false
    }
}

Important: Prefix vs Postfix

java
int a = 5;
int b = a++;  // b = 5, a = 6 (postfix: use then increment)

int c = 5;
int d = ++c;  // d = 6, c = 6 (prefix: increment then use)

7. Ternary Operator: The Conditional Shorthand

The ternary operator is a concise alternative to if-else statements.

java
public class TernaryDemo {
    public static void main(String[] args) {
        int score = 85;
        
        // Traditional if-else
        String grade;
        if (score >= 60) {
            grade = "Pass";
        } else {
            grade = "Fail";
        }
        
        // Ternary equivalent
        String result = (score >= 60) ? "Pass" : "Fail";
        
        // Nested ternary (use with caution)
        String letterGrade = (score >= 90) ? "A" :
                            (score >= 80) ? "B" :
                            (score >= 70) ? "C" :
                            (score >= 60) ? "D" : "F";
        
        System.out.println("Result: " + result);
        System.out.println("Grade: " + letterGrade);
    }
}

8. Instanceof Operator: Type Checking

The instanceof operator checks whether an object is an instance of a specific class or interface.

java
public class InstanceofDemo {
    public static void main(String[] args) {
        String text = "Hello";
        Integer number = 100;
        Object obj = text;
        
        System.out.println(text instanceof String);      // true
        System.out.println(number instanceof Integer);   // true
        System.out.println(obj instanceof String);       // true
        System.out.println(number instanceof Object);    // true (all classes extend Object)
        
        // null check
        String nullString = null;
        System.out.println(nullString instanceof String); // false
        
        // Practical use in polymorphism
        Object[] objects = {"String", 123, 45.67, true};
        
        for (Object objItem : objects) {
            if (objItem instanceof String) {
                System.out.println("Found String: " + objItem);
            } else if (objItem instanceof Integer) {
                System.out.println("Found Integer: " + objItem);
            }
        }
    }
}

Operator Precedence: The Order of Operations

When multiple operators appear in an expression, Java follows specific precedence rules:

java
int result = 5 + 3 * 2;      // 11, not 16 (multiplication before addition)
int another = (5 + 3) * 2;   // 16 (parentheses override precedence)

// Common precedence (highest to lowest)
// 1. Postfix: expr++ expr--
// 2. Unary: ++expr --expr +expr -expr ~ !
// 3. Multiplicative: * / %
// 4. Additive: + -
// 5. Shift: << >> >>>
// 6. Relational: < > <= >= instanceof
// 7. Equality: == !=
// 8. Bitwise AND: &
// 9. Bitwise XOR: ^
// 10. Bitwise OR: |
// 11. Logical AND: &&
// 12. Logical OR: ||
// 13. Ternary: ? :
// 14. Assignment: = += -= etc.

Common Pitfalls and Best Practices

Pitfall 1: Floating-Point Comparisons

java
// Never compare floats/doubles with ==
double a = 0.1 + 0.2;
double b = 0.3;
System.out.println(a == b);  // false! (due to floating-point precision)

// Correct approach
final double EPSILON = 0.000001;
System.out.println(Math.abs(a - b) < EPSILON);  // true

Pitfall 2: Short-Circuit Evaluation

java
// Method that might throw exception
boolean checkValue(int divisor) {
    return divisor != 0 && (10 / divisor) > 2;
}

// This works fine
checkValue(5);  // true
checkValue(0);  // false (doesn't evaluate division)

Best Practice: Use Parentheses for Clarity

java
// Confusing
int result = a + b * c / d - e % f;

// Clear
int result = a + (b * c / d) - (e % f);

Real-World Example: Calculator Application

java
import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter first number:");
        double num1 = scanner.nextDouble();
        
        System.out.println("Enter operator (+, -, *, /, %):");
        char operator = scanner.next().charAt(0);
        
        System.out.println("Enter second number:");
        double num2 = scanner.nextDouble();
        
        double result;
        
        // Using switch with enhanced features (Java 14+)
        result = switch(operator) {
            case '+' -> num1 + num2;
            case '-' -> num1 - num2;
            case '*' -> num1 * num2;
            case '/' -> {
                if (num2 == 0) {
                    throw new ArithmeticException("Division by zero!");
                }
                yield num1 / num2;
            }
            case '%' -> num1 % num2;
            default -> throw new IllegalArgumentException("Invalid operator");
        };
        
        System.out.println("Result: " + result);
        scanner.close();
    }
}
Course Reviews

No reviews yet.