Mastering Java: The Ultimate Quiz for 'Thinking in Java'

Disable ads (and more) with a membership for a one time $2.99 payment

Mastering Java: The Ultimate Quiz for 'Thinking in Java'. Dive deep into Java with multiple-choice questions. Challenge yourself with quiz questions designed to test and improve your understanding of the 'Thinking in Java' book. Get ready for your exam!

Practice this question and more.


Why are wrapper classes used in Java generics?

  1. To allow primitive types as type parameters

  2. For type safety and elimination of casts

  3. To enhance performance

  4. To enable collections to work with primitives

The correct answer is: To allow primitive types as type parameters

Wrapper classes are used in Java generics to allow primitive types as type parameters. This is because generics only accept objects as type parameters, so primitive types cannot be used directly. Wrapper classes, such as Integer and Double, wrap around the primitive types and allow them to be used in generics. Additionally, using primitive types in generics would result in auto-boxing and unboxing, which can cause performance issues. Therefore, options B, C, and D are incorrect as they either do not mention the main purpose of wrapper classes in generics or they suggest incorrect reasons for using them.