SteelReed

Search

Search posts, questions…

Java CoreQuestion 9 / 43

Junior

What are wrapper classes and autoboxing? Why is a == b false for Integer a = 128, b = 128?

Short answer

Autoboxing is Java turning an int into an Integer for you. Numbers from -128 to 127 are reused (cached), so 127 == 127 is true but 128 == 128 is false.

autoboxingwithin -128..127outside rangec == dc.equals(d)Integer c = 128Integer.valueOf(128)cached objectnew object each timefalse: compares identitytrue: compares value

3 points to say:

  1. Compare Integer values with equals.
  2. Turning null into an int throws NullPointerException.
  3. For large numeric data use int, not Integer.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.