Operators

Thinking

Operators are fundamental to any programming language, and in Java, they allow us to perform computations, compare values, and manipulate bits. Understanding the different categories of operators is crucial for writing expressive and efficient code.

Whether you're calculating results, checking conditions, or performing low-level operations, the right use of operators ensures logic is both clean and powerful.

Description

Java provides several types of operators that help you perform various operations. These include:

  • Arithmetic Operators: +, -, *, /, %
  • Logical Operators: && (AND), || (OR), ! (NOT)
  • Relational Operators: ==, !=, <, >, <=, >=
  • Bitwise Operators: &, |, ^, ~, <<, >>
  • Assignment Operators: =, +=, -=, *=, /=, etc.

These operators enable developers to build complex logic, perform calculations, control flow, and manipulate data at the binary level.

Video Resources

Java Operators Explained

Understand all types of operators with examples and use cases.

Examples (code)

Using Arithmetic and Logical Operators


public class OperatorExample {
    public static void main(String[] args) {
        int a = 10, b = 20;

        // Arithmetic
        System.out.println("Addition: " + (a + b));
        System.out.println("Modulus: " + (b % a));

        // Logical
        boolean result = (a < b) && (b > 15);
        System.out.println("Logical AND: " + result);
    }
}
  

Using Bitwise Operators


public class BitwiseExample {
    public static void main(String[] args) {
        int x = 5;  // 0101
        int y = 3;  // 0011

        System.out.println("Bitwise AND: " + (x & y));  // 0001 => 1
        System.out.println("Bitwise OR: " + (x | y));   // 0111 => 7
        System.out.println("Bitwise XOR: " + (x ^ y));  // 0110 => 6
    }
}
  

Real-World Applications

Embedded Systems

Bitwise operators are extensively used in systems programming and device communication.

Game Logic

Arithmetic and logical operators are used for movement, scoring, and AI logic.

Data Filtering

Logical operators help implement complex filtering conditions in database queries.

Interview Questions

Q1: What is the difference between logical AND (&&) and bitwise AND (&)?

Show Answer

Logical AND (&&) operates on boolean expressions and supports short-circuiting. Bitwise AND (&) works on individual bits and does not short-circuit.

Q2: When would you use bitwise operators?

Show Answer

Bitwise operators are used in low-level programming, such as device drivers, cryptography, and performance-critical calculations.

Q3: What is the output of 5 ^ 3 in Java?

Show Answer

It is 6. XOR compares each bit: 0101 ^ 0011 = 0110, which equals 6 in decimal.