SCJP Java Generics, Enums, and Autoboxing 1 — Questions and Answers
Question 1: What is the primary benefit of using generics in Java?
- Improved runtime performance
- Type safety at compile time, eliminating the need for explicit casting (Correct answer)
- Allowing methods to return multiple types
- Enabling dynamic typing
Correct answer: Type safety at compile time, eliminating the need for explicit casting
Generics allow type parameters to be specified at compile time, catching type errors early and eliminating the need for unsafe casts.
Question 2: What is type erasure in Java generics?
- The process of deleting generic classes at compile time
- Removing type parameter information at compile time so the bytecode uses raw types (Correct answer)
- Converting generic types to Object at runtime only
- A compiler optimization for generics
Correct answer: Removing type parameter information at compile time so the bytecode uses raw types
Java implements generics through type erasure: type parameters are removed at compile time and replaced with their bounds (or Object), so no generic type info exists at runtime.
Question 3: What does autoboxing in Java do?
- Converts arrays to ArrayLists automatically
- Automatically converts primitive types to their wrapper class equivalents (Correct answer)
- Boxes multiple return values into a tuple
- Wraps exceptions in RuntimeException
Correct answer: Automatically converts primitive types to their wrapper class equivalents
Autoboxing is the automatic conversion of primitives (like `int`) to their wrapper classes (like `Integer`) when needed by the context.
Question 4: Which of the following correctly declares a generic method in Java?
- public T swap(T a, T b)
- public <T> T swap(T a, T b) (Correct answer)
- public Generic<T> swap(T a, T b)
- public static T swap(T a, T b)
Correct answer: public <T> T swap(T a, T b)
A generic method declares its type parameter `<T>` before the return type: `public <T> T methodName(...)`.
Question 5: What is an enum in Java?
- An interface with constants
- A special class that represents a group of named constants (Correct answer)
- A collection of primitive values
- A type of annotation
Correct answer: A special class that represents a group of named constants
An `enum` is a special Java class that defines a fixed set of named constants, with the ability to have fields, methods, and constructors.
Question 6: What is the result of unboxing a null Integer in Java?
- Returns 0
- Throws IllegalArgumentException
- Throws NullPointerException (Correct answer)
- Returns Integer.MIN_VALUE
Correct answer: Throws NullPointerException
Unboxing a null wrapper (e.g., `Integer i = null; int x = i;`) throws a `NullPointerException` because null cannot be converted to a primitive.
What is the primary benefit of using generics in Java?