SCJP Sun Certified Java Programmer MCQ 3 — Questions and Answers
Question 1: Which interface must be implemented by a class to allow its objects to be sorted using Collections.sort()?
- Comparator
- Comparable (Correct answer)
- Sortable
- Orderable
Correct answer: Comparable
A class must implement Comparable and override compareTo() to allow natural ordering via Collections.sort().
Question 2: What is the purpose of the 'transient' keyword in Java?
- Prevents a variable from being modified
- Excludes a variable from serialization (Correct answer)
- Makes a variable thread-safe
- Marks a variable as temporary in memory
Correct answer: Excludes a variable from serialization
A transient variable is skipped during object serialization and deserialization.
Question 3: Which of the following is true about Java interfaces prior to Java 8?
- Interfaces can have constructors
- All methods in an interface are implicitly public and abstract (Correct answer)
- Interfaces support multiple inheritance of state
- Interface methods can have a body
Correct answer: All methods in an interface are implicitly public and abstract
Before Java 8, all methods in an interface were implicitly public and abstract with no method body.
Question 4: What is the result of casting a double value 9.99 to int in Java?
- 10
- 9 (Correct answer)
- Compile-time error
- Runtime exception
Correct answer: 9
Casting double to int truncates (not rounds) the fractional part, so 9.99 becomes 9.
Question 5: In Java, which exception type must be declared in a method's throws clause or handled with try-catch?
- RuntimeException
- Error
- Checked exception (Correct answer)
- Unchecked exception
Correct answer: Checked exception
Checked exceptions (subclasses of Exception but not RuntimeException) must be declared or handled explicitly.
Question 6: What does the 'static' keyword mean when applied to a class variable?
- The variable cannot change after assignment
- The variable belongs to the class, not to any instance (Correct answer)
- The variable is shared only between subclasses
- The variable is thread-local
Correct answer: The variable belongs to the class, not to any instance
A static variable is shared across all instances of the class and belongs to the class itself.
Question 7: Which of the following is NOT a valid loop construct in Java?
- for
- while
- do-while
- repeat-until (Correct answer)
Correct answer: repeat-until
Java supports for, while, and do-while loops; 'repeat-until' does not exist in Java.
Which interface must be implemented by a class to allow its objects to be sorted using Collections.sort()?