Java Operators
Q1. What are arithmetic operators in Java?
Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, division, and modulo.
Example
Output:
Use: Arithmetic operators are used in calculations such as totals, averages, and formulas.
Example
int a = 10, b = 3;System.out.println(a + b); // additionSystem.out.println(a - b); // subtractionSystem.out.println(a * b); // multiplicationSystem.out.println(a / b); // divisionSystem.out.println(a % b); // moduloOutput:
13
7
30
3
1
Use: Arithmetic operators are used in calculations such as totals, averages, and formulas.
Q2. What are increment and decrement operators in Java?
++ increases a value by 1.
-- decreases a value by 1.
They can be prefix or postfix.
Example
int x = 5;System.out.println(++x); // prefix: first increment then useSystem.out.println(x++); // postfix: first use then incrementSystem.out.println(--x); // prefixSystem.out.println(x--); // postfixOutput:
6
6
4
4
Q3. What is operator precedence in Java and why is it important?
Operator precedence defines the order in which operators are executed.
Example
Example
int result = 10 + 2 * 5;System.out.println(result);Output:20
Q4. How does the ternary operator work in Java?
The ternary operator ?: is a shorthand for if-else.
Example
int age = 18;String result = (age >= 18) ? "Adult" : "Minor";System.out.println(result);Output:
Adult
Q5. What are assignment operators in Java?
Assignment operators (=, +=, -=, *=, /=, %=) assign values and perform operations in a shorter way.
Example
int x = 5; int x = 10; x += 5; // x = x + 5 x *= 2; // x = x * 2 System.out.println(x);
Output:
30