1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 3

CAP477 · Unit 3: Exceptions and wrappers

Wrapper classes, autoboxing and Strings in memory

8 practice questions

Key points

  • Wrappers box primitives for collections
  • Integer cache covers -128 to 127
  • Unboxing null gives NullPointerException
  • Use equals for wrappers and Strings

Each primitive has a wrapper class: byte->Byte, short->Short, int->Integer, long->Long, float->Float, double->Double, char->Character, boolean->Boolean. Wrappers are immutable objects needed by generics and collections (List<int> is illegal).

Autoboxing converts primitive -> wrapper automatically; unboxing does the reverse. Unboxing null throws NullPointerException.

Integer cache: Integer.valueOf (and autoboxing) reuse objects for values -128 to 127. So Integer a = 127, b = 127; a == b is true, but Integer c = 128, d = 128; c == d is false while c.equals(d) is true. Always compare wrappers with `equals`.

Long.equals(Integer) is false even for the same number (different types): Long.valueOf(10).equals(Integer.valueOf(10)) is false.

Useful methods: Integer.parseInt("12") returns int (+1 gives 13), Integer.parseInt("1010", 2) gives 10, Integer.valueOf(12), Integer.toBinaryString(10) = "1010", toHexString(255) = "ff", toOctalString(8) = "10", Integer.compare(3, 7) = -1, Integer.MAX_VALUE, MIN_VALUE. Math.abs(Integer.MIN_VALUE) is still negative (overflow). Double.NaN == Double.NaN is false; use Double.isNaN. Boolean.parseBoolean("TRUE") is true (case-insensitive) and "yes" is false. Character.isDigit, isLetter, toUpperCase, getNumericValue.

List remove trap: on List<Integer>, remove(1) removes index 1 but remove(Integer.valueOf(1)) removes the value 1.

String constants: compile-time concatenation of literals ("a" + "b") is pooled, so == "ab" is true; runtime concatenation (p + "b" with a non-final variable) creates a new object (== false) but intern() returns the pooled one. A final String q = "a" makes q + "b" a compile-time constant (true).

Exam pitfall: == on Integer values above 127 is false.

Try two questions

Question 1 · Tier 3, Apply

String p = "a"; String s3 = p + "b"; String s2 = "ab"; s3 == s2 is:

  1. true
  2. Depends on the JVM only
  3. false
  4. A compile error
Show the answer

C. Runtime concatenation creates a new object; s3.intern() == s2 is true. Results (literal, variable, final, interned): true false true true.

Question 2 · Tier 1, Recall

Why can't a List be declared as List<int>?

  1. int has no default value
  2. Generics accept only reference types, not primitives
  3. List only stores Strings
  4. int is too small
Show the answer

B. Use List<Integer>; autoboxing converts between int and Integer.