Java operators
In Java, an operator is a symbol that performs an operation on one or more operands. Some of the common Java operators are:
1. Arithmetic Operators: +, -, *, /, %
2. Comparison Operators: ==, !=, >, <, >=, <=
3. Logical Operators: &&, ||, !
4. Assignment Operators: =, +=, -=, *=, /=, %=
5. Ternary Operator: ? :
6. Bitwise Operators: &, |, ^, ~, <<, >>, >>>
7. Conditional Operators: instanceof
Each operator has a specific function and precedence in expressions.
Java examples on operators
1. Arithmetic Operators:
int a = 10;
int b = 20;
int c = a + b; // c is 30
int d = b - a; // d is 10
int e = a * b; // e is 200
int f = b / a; // f is 2
int g = b % a; // g is 0
2.Comparison Operators:
int a = 10;
int b = 20;
if (a == b) {
System.out.println("a is equal to b");
} else {
System.out.println("a is not equal to b");
}
if (a > b) {
System.out.println("a is greater than b");
} else {
System.out.println("a is not greater than b");
}
3.Logical Operators:
boolean a = true;
boolean b = false;
if (a && b) {
System.out.println("Both a and b are true");
} else {
System.out.println("Either a or b is false");
}
if (a || b) {
System.out.println("Either a or b is true");
} else {
System.out.println("Neither a nor b is true");
}
if (!a) {
System.out.println("a is false");
} else {
System.out.println("a is true");
}
4. Assignment Operators:
int a = 10;
int b = 20;
a += b; // a is now 30
b -= a; // b is now -10
a *= b; // a is now -300
b /= a; // b is now 0
5. Ternary Operator:
int a = 10;
int b = 20;
int min = (a < b) ? a : b;
6.Bitwise Operators:
int a = 10;
int b = 20;
int c = a & b; // c is 0
int d = a | b; // d is 30
int e = a ^ b; // e is 30
int f = ~a; // f is -11
int g = a << 2; // g is 40
int h = b >> 2; // h is 5
7. Conditional Operator:
String str = "Hello";
if (str instanceof String) {
System.out.println("str is an instance of String");
} else {
System.out.println("str is not an instance of String");
}
Java operators
Reviewed by Mukesh Jha
on
10:07 PM
Rating:

No comments:
Add your comment