Operators in Java are **symbols** that perform operations on variables and values. Java has different types of operators for various computations.
Operators in Java
What are Operators?
Operators in Java are **symbols** that perform operations on variables and values. Java has different types of operators for various computations.
Types of Operators in Java
Java supports the following types of operators:
- Arithmetic Operators
- Relational (Comparison) Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Unary Operators
- Ternary Operator
1. Arithmetic Operators
These operators perform mathematical operations like addition, subtraction, multiplication, and division.
Example:
public class ArithmeticExample {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
System.out.println("Modulus: " + (a % b));
}
}
2. Relational (Comparison) Operators
These operators compare values and return **true** or **false**.
Example:
public class RelationalExample {
public static void main(String[] args) {
int x = 10, y = 5;
System.out.println(x > y); // true
System.out.println(x < y); // false
System.out.println(x == y); // false
System.out.println(x != y); // true
}
}
3. Logical Operators
These operators are used to combine **boolean** expressions.
Example:
public class LogicalExample {
public static void main(String[] args) {
boolean a = true, b = false;
System.out.println(a && b); // false
System.out.println(a || b); // true
System.out.println(!a); // false
}
}
4. Bitwise Operators
These operators perform bit-level operations.
Example:
public class BitwiseExample {
public static void main(String[] args) {
int a = 5, b = 3;
System.out.println(a & b); // 1 (AND)
System.out.println(a | b); // 7 (OR)
System.out.println(a ^ b); // 6 (XOR)
}
}
5. Assignment Operators
Used to assign values to variables.
Example:
public class AssignmentExample {
public static void main(String[] args) {
int x = 10;
x += 5; // Same as x = x + 5
System.out.println(x); // 15
}
}
6. Unary Operators
These work on a single operand.
Example:
public class UnaryExample {
public static void main(String[] args) {
int num = 5;
System.out.println(++num); // 6 (Pre-increment)
System.out.println(num--); // 6 (Post-decrement)
}
}
7. Ternary Operator
Shorthand for if-else conditions.
Example:
public class TernaryExample {
public static void main(String[] args) {
int a = 10, b = 20;
int min = (a < b) ? a : b;
System.out.println("Smaller number: " + min);
}
}
Conclusion
Operators are essential for performing various operations in Java. Understanding them helps in writing efficient code.
📌 Next Topic: Control Statements in Java