🔢 Operators
Master the use of operators to perform calculations, compare values, and manipulate bits at the lowest level.
Overview of Operators
Java provides a rich set of operators to manipulate variables. We can divide them into the following groups:
Arithmetic & Assignment Operators
Arithmetic operators are used to perform common mathematical operations. Assignment operators are used to assign values to variables, often combined with arithmetic operators.
public class ArithmeticDemo { public static void main(String[] args) { int x = 10, y = 3; System.out.println("Add: " + (x + y)); // 13 System.out.println("Modulus: " + (x % y)); // 1 (Remainder) x += 5; // Equivalent to x = x + 5; (Now x is 15) x++; // Unary increment: x becomes 16 } }
Relational & Logical Operators
Relational operators compare two values and return a boolean. Logical operators combine boolean expressions.
- Relational:
==, !=, >, <, >=, <= - Logical:
&&(Logical AND),||(Logical OR),!(Logical NOT)
&& and || exhibit "short-circuit" behavior. If the first operand evaluates to false for AND, the second operand is never evaluated.
Bitwise Operators
Bitwise operators work on individual bits of integer data types.
public class BitwiseDemo { public static void main(String[] args) { int a = 5; // 0101 int b = 3; // 0011 System.out.println("a & b: " + (a & b)); // 0001 = 1 System.out.println("a | b: " + (a | b)); // 0111 = 7 System.out.println("a ^ b: " + (a ^ b)); // 0110 = 6 System.out.println("a << 1: " + (a << 1));// 1010 = 10 (Left shift) } }
Ternary Operator (?:)
A shorthand for an if-else statement. It returns one of two values depending on a boolean condition.
public class TernaryDemo { public static void main(String[] args) { int age = 20; String status = (age >= 18) ? "Adult" : "Minor"; System.out.println(status); // Outputs: Adult } }
Operator Precedence
Expressions are evaluated based on operator precedence rules. Higher precedence operators are evaluated first. You can always use parentheses () to explicitly define the order of evaluation.
int result = 10 + 5 * 2; // result is 20, because * has higher precedence than + int result2 = (10 + 5) * 2; // result2 is 30, due to parentheses