BhauAutomation

Operators in Java

Operators in Java are special symbols used to perform operations on variables and values, helping in performing calculations, comparisons, and logical decisions effectively.

What are Operators in Java?

Operators are special symbols that perform specific operations on one, two, or three operands and then return a result. They make programming more efficient and logical.

Example:
int a = 10, b = 5;
int sum = a + b; // '+' is an arithmetic operator
System.out.println(sum); // Output: 15
    

Types of Operators in Java

Arithmetic Operators perform mathematical operations like addition, subtraction, multiplication, division, and modulus.

Example:
int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a % b); // 1
    

Relational Operators compare two values and return a boolean result (true/false).

Example:
int a = 10, b = 5;
System.out.println(a > b);  // true
System.out.println(a == b); // false
    

Logical Operators are used to perform logical operations such as AND, OR, and NOT.

Example:
int x = 10, y = 20;
System.out.println(x > 0 && y > 0); // true
System.out.println(!(x > y));       // true
    

Assignment Operators are used to assign values to variables.

Example:
int num = 10;
num += 5; // same as num = num + 5
System.out.println(num); // Output: 15
    

Unary Operators operate on a single operand and perform increment/decrement or negation operations.

Example:
int a = 10;
System.out.println(++a); // 11
System.out.println(-a);  // -11
    

Bitwise Operators perform operations on bits and are mostly used in low-level programming or optimization.

Example:
int a = 5, b = 3;
System.out.println(a & b); // 1 (AND)
System.out.println(a | b); // 7 (OR)
    

Ternary Operator is a shorthand version of if-else.

Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max); // 20
    

Advantages of Using Operators

Operators simplify program logic, make expressions concise, and enhance code readability. They also enable complex decision-making and data manipulation effectively.

Important Points

Operators follow a strict precedence and associativity order. Division by zero using '/' operator throws an ArithmeticException. Increment and decrement operators work only on numeric data types.

Example Program

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

        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a > b = " + (a > b));
        System.out.println((a > 0) && (b > 0));
        System.out.println("++a = " + (++a));
    }
}
  

Best Practices

Always use parentheses to make expressions clear and avoid confusion. Test for division by zero before performing division. Write meaningful and simple operator expressions for better readability.