1Z0-811 1Z0-811 Java Operators and Control Flow 2 — Questions and Answers
Question 1: What is the difference between `==` and `.equals()` when comparing String objects in Java?
- `==` compares content; `.equals()` compares references
- `==` compares references; `.equals()` compares content (Correct answer)
- Both compare content
- Both compare references
Correct answer: `==` compares references; `.equals()` compares content
`==` compares object references (memory addresses), while `.equals()` on String compares the actual character content.
Question 2: Which loop is guaranteed to execute its body at least once?
- for loop
- while loop
- do-while loop (Correct answer)
- enhanced for loop
Correct answer: do-while loop
The `do-while` loop evaluates its condition after executing the body, so it always runs at least once regardless of the condition.
Question 3: What is the correct syntax for a `switch` statement's default case in Java?
- else: { }
- otherwise: { }
- default: { } (Correct answer)
- case default: { }
Correct answer: default: { }
The `default` keyword in a switch statement defines the block that executes when no other case matches.
Question 4: Which of the following correctly describes the `break` statement in a `switch` block?
- It exits the entire program
- It is automatically inserted by the compiler
- It prevents fall-through to the next case (Correct answer)
- It skips only one case label
Correct answer: It prevents fall-through to the next case
Without a `break` statement, execution falls through to the next case in a switch block; `break` prevents this by exiting the switch.
Question 5: What is the output of `int i = 0; while(i < 3) { System.out.print(i + " "); i++; }`?
- 1 2 3
- 0 1 2 (Correct answer)
- 0 1 2 3
- 1 2
Correct answer: 0 1 2
The loop prints i (starting at 0) and increments it after each print, running while i < 3, so it outputs 0, 1, and 2.
Question 6: What does the compound assignment operator `+=` do?
- Adds two values and stores the result in a new variable
- Adds the right operand to the left operand and assigns the result to the left operand (Correct answer)
- Checks if the left value is greater than the right
- Concatenates two strings only
Correct answer: Adds the right operand to the left operand and assigns the result to the left operand
The `+=` operator adds the right operand to the left operand and stores the result back in the left operand (e.g., `x += 3` is equivalent to `x = x + 3`).
What is the difference between `==` and `.equals()` when comparing String objects in Java?