How to create wrapper objects in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

Each primitive type in Java has a corresponding built-in wrapper class, and these wrapper classes are also immutable. Integer, Float, Double, Byte, and etc.. are some of the built-in wrapper classes. The main incentive of using such wrappers in our code is accessing type information about the corresponding primitive type, Auto-Boxing feature, where a primitive data is automatically promoted to an object reference type, and moving primitive type data around data structures.

We can create an instance of Wrapper Classes by using a new operator, and also use the valueOf() method within types such as Integer to create a wrapper object. The Integer.valueOf() method will reuse existing Integer objects with the same value on the heap. If an object with the same value is present in the heap, it will return a reference to an existing object, or else returns the reference of the newly created Integer object.

In the below code snippets, we can able to create wrapper objects in JShell tool.

Snippet-1

jshell> Integer int1 = new Integer(10);
int1 ==> 10

jshell> Integer int2 = new Integer(10);
int2 ==> 10

jshell> Integer int3 = Integer.valueOf(10);
int3 ==> 10

jshell> Integer int4 = Integer.valueOf(10);
int4 ==> 10

jshell> int1 == int2;
$7 ==> true

jshell> int3 == int4;
$8 ==> true

Snippet-2

jshell> Integer abc1 = Integer.valueOf(700);
abc1 ==> 700

jshell> Integer abc2 = 700;
abc2 ==> 700

jshell> Integer abc3 = 700;
abc3 ==> 700

jshell> abc2 == abc3
$4 ==> false

jshell> Integer.MAX_VALUE
$5 ==> 2147483647

jshell> Integer.MIN_VALUE
$6 ==> -2147483648

jshell> Integer.SIZE
$7 ==> 32

jshell> Integer.BYTES
$8 ==> 4
raja
Published on 24-Apr-2020 14:18:37
Advertisements