Text preview & study summary
Java Programming Fundamentals
A free sample of 5 questions from this quiz, shown in full with answer choices and explanations. No interactivity — everything is visible on this page for study and review.
Want to test your knowledge? Launch the Interactive Exam Simulator
Question 1
What is the output of this Java code?
```java
public class Test {
public static void main(String[] args) {
int i = 0;
while (i < 3) {
System.out.print(i + " ");
i++;
}
}
}
```
Explanation
The loop runs while `i < 3`, so it executes for i=0, i=1, i=2. After printing 2 and incrementing to 3, the condition `3 < 3` is false and the loop ends. Output is `0 1 2 ` (with trailing space from `i + " "`). The closest answer is C. This tests basic while loop understanding and the pre-increment behavior.
Question 2
**Statement:** In Java, the `StringBuilder` class is preferred over `String` concatenation in loops because `String` objects are immutable and each concatenation creates a new `String` object in memory.
Explanation
Java `String` objects are immutable—concatenation with `+` creates a new `String` object each time. Inside loops, this generates significant garbage. `StringBuilder` (non-thread-safe) and `StringBuffer` (thread-safe) use a mutable character buffer and are far more efficient for repeated string building operations. Modern Java compilers optimize simple single-line concatenation, but loop concatenation should use `StringBuilder`.
Question 3
Which of the following Java statements about **checked vs. unchecked exceptions** is CORRECT?
Explanation
Checked exceptions (e.g., IOException, SQLException) extend `Exception` directly and MUST be either caught in a try-catch block or declared with `throws` in the method signature. Unchecked exceptions (e.g., NullPointerException, ArrayIndexOutOfBoundsException) extend `RuntimeException` and are not required to be caught or declared—though they can be. There is no `@Unchecked` annotation.
Question 4
In Java, a class that cannot be instantiated directly and may contain both abstract methods and concrete methods is called an [[blank1]] class.
Explanation
An `abstract` class is declared with the `abstract` keyword. It can contain both abstract methods (no body) and concrete methods (with body). It cannot be instantiated directly—only subclasses that implement all abstract methods can be instantiated. Abstract classes are used when you want to provide partial implementation with a template for subclasses to complete.
Question 5
In Java, what does the `volatile` keyword guarantee when applied to a variable?
Explanation
The `volatile` keyword guarantees visibility: when a thread writes to a volatile variable, the updated value is immediately flushed to main memory and other threads always read from main memory rather than local CPU cache. It does NOT provide atomicity or mutual exclusion for compound operations (like `i++`). For atomic operations, use `AtomicInteger` or `synchronized` blocks.
