Java Operators are the symbols that performs operations. Java contains different types of operators like Arithmetic Operator, Logical Operator, Relational Operator, Bitwise Operators, Shift Operators, Assignment Operators, Conditional Operator, InstanceOf Operator.
OR
In Java, operators are symbols or keywords used to perform operations on variables and values.
Types of Java Operators
1. Arithmetic Operators
Used to perform basic mathematical operations.
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
Used to compare two values.
Example:
public class ComparisonExample {
public static void main(String[] args) {
int x = 10, y = 20;
System.out.println(x == y); // false
System.out.println(x != y); // true
System.out.println(x > y); // false
System.out.println(x < y); // true
System.out.println(x >= y); // false
System.out.println(x <= y); // true
}
}
3. Logical Operators
Used to combine multiple conditions.
Example:
public class LogicalExample {
public static void main(String[] args) {
boolean condition1 = (5 > 3);
boolean condition2 = (6 > 10);
System.out.println(condition1 && condition2); // false
System.out.println(condition1 || condition2); // true
System.out.println(!condition1); // false
}
}
4. Assignment Operators
Used to assign values to variables.
Example:
public class AssignmentExample {
public static void main(String[] args) {
int a = 10;
a += 5; // a = a + 5
System.out.println("a += 5: " + a);
}
}
5. Unary Operators
Operate on a single variable.
Example:
public class UnaryExample {
public static void main(String[] args) {
int a = 5;
System.out.println("a: " + a);
System.out.println("++a: " + ++a); // Pre-increment
System.out.println("a++: " + a++); // Post-increment
System.out.println("a: " + a);
}
}
6. Ternary Operator
A shorthand for an if-else condition.
Syntax:
condition ? value1 : value2
Example:
public class TernaryExample {
public static void main(String[] args) {
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum value: " + max);
}
}
Java Operators – Interview Questions
Q 1: What are operators in Java?
Q 2: Name different types of operators in Java.
Q 3: What is an arithmetic operator?
Q 4: What is a logical operator?
Q 5: What is the use of assignment operator?
Java Operators – Objective Questions (MCQs)
Q1. Which of the following is the correct syntax for the ternary operator in Java?
Q2. What is the result of the following expression: 10 + 30 * 3?
Q3. Which operator is used to compare two values for equality in Java?
Q4. What will be the result of the following Java code?int x = 5;
x += 3 * 2;
Q5. Which of the following is a bitwise operator in Java?