Introduction to JVM Languages
上QQ阅读APP看书,第一时间看更新

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.