Wrapper class
Wrapper classes are object equivalents of the 8 primitive types in java.lang. They let primitives be used where an object is required β generics, collections, reflection.
The wrappers
byte | β | Byte |
short | β | Short |
int | β | Integer |
long | β | Long |
float | β | Float |
double | β | Double |
char | β | Character |
boolean | β | Boolean |
Autoboxing and unboxing
List<Integer> nums = new ArrayList<>();
nums.add(42); // autobox: int β Integer
int first = nums.get(0); // auto-unbox: Integer β int
Utility methods
int n = Integer.parseInt("42");
String s = Integer.toString(255, 16); // "ff"
int max = Integer.MAX_VALUE; // 2147483647
boolean odd = n % 2 != 0;
int compare = Integer.compare(a, b);
Watch out: == on wrappers
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b); // false β reference comparison
System.out.println(a.equals(b)); // true β value comparison
Always use .equals() for wrapper comparison. == works accidentally for small values (β128 to 127) due to Integer caching, but never rely on it.