help me in Java References

Output of this program is:-

null

Can someone please tell me why it is null. I thought that it should print the same value as of y, which is the address(reference) of the new Node.

class Node{
	int data;
	Node left, right;
	public Node(){
    	data=0;
    	left=null;
    	right=null;
	}
}
public class aaa{
     	public static void main(String[] args){
       	Node x=new Node();
    	Node y=x.left;
  		y=new Node();
     	System.out.println(x.left);
        }
}

First, you are setting the Value of y = x.left and then setting it back to new Node.

Second, you didn’t even set anything for values what do u expect other than null?

1 Like

Not sure why you expect something different.

int x = 0;
int y = x;
y = 5;
System.out.println(x);

The output is of course 0, and not 5.

1 Like

check the order of your statements.

    class Node{
    int data;
    Node left, right;
    public Node(){
        data=0;
        left=null;
        right=null;
    }
}
public class aaa{
    public static void main(String[] args){
        Node x=new Node();
        Node y=new Node();
        x.left = y;
        y.data = 5;


        System.out.println(x.left.data);
    }
}

Maybe this is what you were looking for.
What you were doing was setting X’s left to a node that wasn’t even created in the first place.(No actually you were doing the opposite, which again is the source of your confusion).
Hope this helped.