Asking that printing object gives real value of objets or it is generated when we use it in java

Viewed 32

So,I am learning Linked list.And decided to print the value of object to confirm that I am thinking right or wrong but

when I am printing the object then it gives different numbers and I print them all together in Output 1

then I comment all the printed lines and then run another time with only two values i.e n2,n3

This time the value is not same as above

So my conculison is running all same time give different numbers(hashCode) to different objects but those numbers are generated at runtime not used to reference the object

getClass().getName() + '@' + Integer.toHexString(hashCode())

I am talking about this hashcode

So I am not able to come on answer

Read some answeres on Stackoverflow but not same question as mine Link 1 , Link 2

here is my code

package LinkedLIst;
    public class Linkedlist_two {
    class Node{
        int data;
        Node next;

        Node(int data){
            this.data = data;
            this.next= null;
        }
    }

    public Node nodeCreation()
    {
        Node n1 = new Node(10);
        Node n2 = new Node(20);
        Node n3 = new Node(30);

        Node head;
        head = n1;
        n1.next = n2;
        n2.next = n3;

        
        //Printing the hash code of the object
        System.out.println(head);
        System.out.println(n1);
        System.out.println(n2);
        System.out.println(n3);

        System.out.println("\nOUTPUT 2\n");
        System.out.println(n2);
        System.out.println(n3);

     return head;
    }

    public static void main(String[] args) {
        Linkedlist_two linkedlist_two = new Linkedlist_two();
        Node head = linkedlist_two.nodeCreation();
    }
}

// Output 1

    /*

      LinkedLIst.Linkedlist_two$Node@16c0663d
      LinkedLIst.Linkedlist_two$Node@16c0663d
      LinkedLIst.Linkedlist_two$Node@3c5a99da  --> n2
      LinkedLIst.Linkedlist_two$Node@47f37ef1  --> n3

    */

// Output 2

      /*

       LinkedLIst.Linkedlist_two$Node@ea4a92b --> n2
      LinkedLIst.Linkedlist_two$Node@3c5a99da --> n3

      */

Getting different output everytime and using all without comment give same value for n1 and n2 Made me think that it is only created and stored when we are using it only.

Thanks in advance for your valuable time.

0 Answers
Related