➗ Operators in Java
In Java, operators are special symbols used to perform operations on variables and values. Java has a rich set of operators that can be categorized into several types.
🧮 Types of Operators in Java
Arithmetic Operators
+
,-
,*
,/
,%
- Used to perform mathematical operations.
Relational Operators
==
,!=
,>
,<
,>=
,<=
- Used to compare two values.
Logical Operators
&&
,||
,!
- Used to perform logical operations (AND, OR, NOT).
Assignment Operators
=
,+=
,-=
,*=
,/=
- Used to assign values to variables.
Unary Operators
+
,-
,++
,--
,!
- Used to perform operations on a single operand.
Bitwise Operators
&
,|
,^
,<<
,>>
- Used to perform bit-level operations.
Ternary Operator
condition ? expression1 : expression2
- A shorthand for
if-else
statement.
Instanceof Operator
- Used to check if an object is an instance of a specific class.
🧪 Example: Arithmetic and Relational Operators
public class OperatorsExample {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("Addition: " + (a + b)); // 15
System.out.println("Subtraction: " + (a - b)); // 5
System.out.println("Is a > b? " + (a > b)); // true
}
}
⚙️ Operator Precedence
Operator precedence determines the order in which operators are evaluated. For example, multiplication and division have higher precedence than addition and subtraction.