Wrapper Classes in Java - Quiz

Total: 3 questions

1. 

What are wrapper classes in Java, and why do we need them?

Wrapper classes from the java.lang package hold a single primitive value as an object. Each of the eight primitive types has its own wrapper: Byte, Short, Integer, Long, Float, Double, Character, Boolean. The name matches the primitive, capitalized; the exceptions are Integer (int) and Character (char).

Wrappers let you:

  • store numbers in collections and generics (List<Integer> — List<int> does not compile);
  • represent a missing value with null;
  • convert strings to numbers and back (Integer.parseInt(), Integer.toString());
  • use constants and utility methods (Integer.MAX_VALUE, Character.isDigit(), Double.isNaN()).

Wrapper objects are immutable. The numeric wrappers extend the abstract class Number; Character and Boolean do not.

2. 

Why are constructors like new Integer(42) deprecated, and what should you use instead?

The constructors of all wrapper classes (new Integer(42), new Integer("42"), new Boolean("true") and so on) were deprecated in Java 9, and since Java 16 they are marked @Deprecated(forRemoval = true) (JEP 390): they may be removed in a future release, and the compiler issues a warning.

The main reason: a constructor always creates a new object, while valueOf() may return an existing object from the cache, which saves memory. Wrappers are also treated as value-based classes, whose object identity should not matter.

Integer i1 = 42;                        // autoboxing
Integer i2 = Integer.valueOf("42");     // from a string
Boolean b1 = Boolean.valueOf("true");
Character c1 = Character.valueOf('c');
3. 

What is the difference between Integer.valueOf(String) and Integer.parseInt(String)? What happens if the string is not a number?

Both methods parse a string; the difference is the return type. Integer.valueOf("42") returns an Integer object, while Integer.parseInt("42") returns a primitive int. Internally, valueOf(String) calls parseInt() and boxes the result.

int count = Integer.parseInt("42");      // primitive, no object
Integer boxed = Integer.valueOf("42");   // Integer object
int bin = Integer.parseInt("101011", 2); // 43, with a radix

If you need an int, use parseInt(); if you need an object (for a collection or a nullable field), use valueOf().

For an invalid string, both methods throw the unchecked NumberFormatException: for example, for " 42" (whitespace is not trimmed), "4.2", "abc" and even null. Boolean.parseBoolean()/Boolean.valueOf() are the exception: they never throw and return false for any string other than "true" in any letter case.

Page 1 of 1