How to declare reference types in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

JShell is an interactive tool in Java 9 that allows user inputs, evaluates it, and prints output to the user.

Unlike a value type, a reference type doesn't store its value directly. Instead, it will store the address where a value is stored. It means that a reference type contains a pointer to another memory location that holds the data. The reference types are String, arrays, class, and delegates.

In the below code snippet, when we create a new instance of Animal, it can be created on the heap memory. The new Animal() creates an object on the Heap. Animal@73846619, the object is stored on the Heap at address 73846619.


jshell> class Animal {
   ...> }
| created class Animal

jshell> Animal dog = new Animal();
dog ==> Animal@73846619

In the below code snippet, two new Animal objects are created on the Heap. Their memory locations (references) are stored in the reference variables dog and cat. In Java, all classes are Reference Types. Except for primitive variable instances, all the instances or objects are stored on the Heap. The references to the objects are stored in the reference variables like dog and cat.


jshell> class Animal {
   ...>    int id;
   ...>    public Animal(int id) {
   ...> = id;
   ...>    }
   ...> }
| created class Animal

jshell> Animal dog = new Animal(10);
dog ==> Animal@6adede5

jshell> Animal cat = new Animal(20);
cat ==> Animal@5025a98f

In the below code snippet, "j = I" copies the value of  "I" into "j". Later, when the value of "j" is changed, "I" is not affected. By using primitive variables, compares their values.


jshell> int i = 5;
i ==> 5

jshell> int j;
j ==> 0

jshell> j = i;
j ==> 5

jshell> j = 10;
j ==> 10

jshell> i;
i ==> 5

jshell> i == j;
$11 ==> false

jshell> j = 5;
j ==> 5

jshell> i == j;
$13 ==> true
Published on 24-Apr-2020 23:16:37