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.
int a = 10, b = 5;
int sum = a + b; // '+' is an arithmetic operator
System.out.println(sum); // Output: 15
Types of Operators in Java
Perform mathematical operations like addition, subtraction, multiplication, division, and modulus.
int a = 10, b = 3;
System.out.println(a + b); // 13
System.out.println(a % b); // 1
Compare two values and return a boolean result (true/false).
int a = 10, b = 5;
System.out.println(a > b); // true
System.out.println(a == b); // false
Perform logical operations such as AND, OR, and NOT.
int x = 10, y = 20;
System.out.println(x > 0 && y > 0); // true
System.out.println(!(x > y)); // true
Used to assign values to variables.
int num = 10;
num += 5; // same as num = num + 5
System.out.println(num); // Output: 15
Operate on a single operand and perform increment/decrement or negation operations.
int a = 10;
System.out.println(++a); // 11
System.out.println(-a); // -11
Perform operations on bits, mostly used in low-level programming or optimization.
int a = 5, b = 3;
System.out.println(a & b); // 1 (AND)
System.out.println(a | b); // 7 (OR)
A shorthand version of if-else.
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