- Introduction to JVM Languages
- Vincent van der Leun
- 91字
- 2021-07-02 21:46:28
Autoboxing examples
Let's pass a primitive integer to a reference type variable that expects an instance of the java.lang.Integer class:
int primitiveInt = 42;
Integer wrappedInteger = primitiveInt;
A new Integer object will be instantiated that could wrap the 42 primitive integer value. This will have the same effect as that of creating a new Integer instance yourself:
Integer wrappedInteger = new Integer(42);
Specifying two Integer instances to an API that requires two primitive int values as parameters also works as expected:
System.out.println("Hello world".substring(new Integer(0),
new Integer(5)));
This will print Hello.