Autoboxing
Description
Java can wrap a primitive automatically.
Explanation
This happens when an object is required.
Example
Integer score = 92;← Chapter 7 — Input, Wrappers & Lambdas
mixed
Wrapper classes represent primitive values as objects. For example, Integer wraps int and Double wraps double.
Wrappers are needed by generic collections and provide parsing utilities. Java can automatically convert between a primitive and its wrapper in many common situations.
Java can wrap a primitive automatically.
This happens when an object is required.
Integer score = 92;Wrapper methods convert String values.
Invalid numeric text throws NumberFormatException.
int score = Integer.parseInt("92");Use primitive types for simple calculations unless an object is required. A wrapper variable can be null, so unboxing a null wrapper causes NullPointerException.
public class WrapperDemo {
public static void main(String[] args) {
String scoreText = "92";
Integer score = Integer.parseInt(scoreText);
System.out.println(score + 8);
}
}