Java Operators - Detailed Notes
What are Operators?
Operators are symbols that perform operations on variables and values in Java.
Types of Operators in Java
Java provides different types of operators:
1. Arithmetic Operators
Used for basic mathematical operations.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)
Example:
int a = 10, b = 3;
[Link]("Addition: " + (a + b)); // 13
[Link]("Remainder: " + (a % b)); // 1
2. Relational (Comparison) Operators
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater or equal to
<= Less or equal to
Example:
int x = 10, y = 20;
[Link](x > y); // false
[Link](x != y); // true
3. Logical Operators
&& Logical AND
|| Logical OR
! Logical NOT
Example:
boolean cond1 = true, cond2 = false;
[Link](cond1 && cond2); // false
[Link](cond1 || cond2); // true
4. Assignment Operators
= Assignment
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/=: Divide and assign
%=: Modulus and assign
Example:
int z = 10;
z += 5; // z = z + 5
[Link](z); // 15
5. Unary Operators
++ Increment
-- Decrement
+ Positive sign
- Negative sign
! Logical NOT
Example:
int p = 5;
[Link](p++); // Prints 5, then p becomes 6
[Link](++p); // p becomes 7, then prints 7
6. Bitwise Operators
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
<< Left shift
>> Right shift
7. Ternary Operator
(condition) ? value_if_true : value_if_false
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Max: " + max); // Max: 20
Complete Java Program Demonstrating All Operators:
public class OperatorsDemo {
public static void main(String[] args) {
int a = 10, b = 5;
// Arithmetic
[Link]("Addition: " + (a + b));
// Relational
[Link]("Is a > b? " + (a > b));
// Logical
boolean cond = (a > b) && (b > 0);
[Link]("Logical AND: " + cond);
// Assignment
a += 5;
[Link]("a after += : " + a);
// Ternary
int max = (a > b) ? a : b;
[Link]("Max: " + max);
}
}