📚 Quick Study Guide: Java Arithmetic Operators
- ➕ Addition (`+`): Used to sum two operands. Example: `$a + b$`.
- ➖ Subtraction (`-`): Used to find the difference between two operands. Example: `$a - b$`.
- ✖️ Multiplication (`*`): Used to multiply two operands. Example: `$a * b$`.
- ➗ Division (`/`): Divides the first operand by the second. For integers, it performs integer division (truncates decimals). For floating-point types, it yields a precise result. Example: `$a / b$`.
- ➗ Modulus (`%`): Returns the remainder of the division of the first operand by the second. Works for integer and floating-point types. Example: `$a % b$`.
- ⬆️ Increment (`++`): Increases the value of an operand by 1. Can be pre-increment (`++a`) or post-increment (`a++`).
- ⬇️ Decrement (`--`): Decreases the value of an operand by 1. Can be pre-decrement (`--a`) or post-decrement (`a--`).
- ⚖️ Operator Precedence: Multiplication, Division, and Modulus have higher precedence than Addition and Subtraction. Parentheses `()` can be used to override precedence.
- 🔄 Compound Assignment Operators: Combine an arithmetic operator with the assignment operator (e.g., `+=`, `-=`, `*=`, `/=`, `%=`). Example: `$x += 5$` is equivalent to `$x = x + 5$`.
- 💡 Type Promotion: If operands are of different types, Java promotes the smaller type to the larger type before performing the operation (e.g., `int` to `double`) to prevent data loss.
🧠 Practice Quiz: Java Arithmetic Operators
1. What is the result of the following Java expression?
int result = 10 / 3;
2. Which operator returns the remainder of a division?
3. Consider the following code snippet:
int x = 5;
int y = x++;
What are the values of x and y after these operations?
- A) x = 5, y = 5
- B) x = 6, y = 5
- C) x = 5, y = 6
- D) x = 6, y = 6
4. What will be the output of the following Java code?
System.out.println(2 + 3 * 4);
5. Which of the following is equivalent to a = a * b;?
- A) a *= b;
- B) a =* b;
- C) a = b*;
- D) a * b = a;
6. If int num = 15;, what is the value of num % 4;?
7. What is the final value of result?
double d1 = 10.0;
int i1 = 3;
double result = d1 / i1;
- A) 3
- B) 3.0
- C) 3.3333333333333335
- D) 3.33
Click to see Answers
1. B
2. C
3. B
4. B
5. A
6. A
7. C