NullPointerException when an object is initialized in another way

I tried to learn about binary trees and NullPointerException. So I decided to write a small program in order to try to understand it. Here is the code:

public class Nulls
{
    static Node node;
    private class Node
    {
        int val;
        Node right;
        Node left;
    }
    public void init(Node n)
    {
        if(n==null)n=new Node();
    }
    public void print()
    {
         System.out.println(node);
    }
    public static void main(String[] args)
    {
        Nulls n=new Nulls();
        n.init(node);
        n.print();
    }
}

There was a way out null. If I understood correctly, the node object was initialized, and the output should be an object method toString(). And since the method print()is executed after init(Node n), the output should not be null. What is the problem?

+4
source share
1 answer

, Java , , () node n node, null. , , node, init, GC, init .

:

public class Nulls {

    static Node node;

    private class Node {
        int val;
        Node right;
        Node left;
    }

    public void init() {
        if(node==null) {
            node=new Node();
        }
    }

    public void print() {
        System.out.println(node);
    }

    public static void main(String[] args) {
        Nulls n=new Nulls();
        n.init();
        n.print();
    }
}
+6

All Articles