SCJP Basic 4 — Questions and Answers
Question 1: What happens when you assign a larger numeric type to a smaller one without casting in Java?
- Java auto-narrows it
- Compile-time error (Correct answer)
- Runtime exception
- Data is silently truncated
Correct answer: Compile-time error
Narrowing conversions require an explicit cast; without one, the compiler produces an error.
Question 2: Which loop is guaranteed to execute its body at least once?
- for
- while
- do-while (Correct answer)
- enhanced for
Correct answer: do-while
A do-while loop checks its condition after executing the body, so it always runs at least once.
Question 3: What is the output of: System.out.println("Hello" + 1 + 2);?
- Hello3
- Hello12 (Correct answer)
- 3Hello
- Compile error
Correct answer: Hello12
String concatenation is left-to-right; "Hello" + 1 = "Hello1", then "Hello1" + 2 = "Hello12".
Question 4: Which of the following is true about Java's 'break' statement in a switch block?
- It exits the entire program
- It skips to the next case without executing it
- It prevents fall-through to the next case (Correct answer)
- It is required in every case
Correct answer: It prevents fall-through to the next case
Without break, execution falls through to subsequent cases; break exits the switch block.
Question 5: What is the purpose of the 'this' keyword in Java?
- It refers to the parent class
- It refers to the current object instance (Correct answer)
- It creates a new object
- It refers to the class itself
Correct answer: It refers to the current object instance
The 'this' keyword is a reference to the current object within an instance method or constructor.
Question 6: Which of the following correctly defines a constructor in Java?
- void MyClass() {}
- MyClass MyClass() {}
- MyClass() {} (Correct answer)
- static MyClass() {}
Correct answer: MyClass() {}
A constructor has the same name as the class and no return type, not even void.
Question 7: What is method overloading in Java?
- Providing a new implementation for a parent class method
- Defining multiple methods with the same name but different parameter lists (Correct answer)
- Making a method run faster
- Preventing a method from being overridden
Correct answer: Defining multiple methods with the same name but different parameter lists
Overloading lets you define multiple methods with the same name differing in number or type of parameters.
What happens when you assign a larger numeric type to a smaller one without casting in Java?