Why doesn’t this statement throw a StackOverflowError?

NIL is a static variable. It is initialized one time, when the class is initialized. When it is initialized, a single Node instance is created. The creation of that Node doesn’t trigger creation of any other Node instances, so there is not infinite chain of calls. Passing Node.NIL to the constructor call has the same effect as passing null, since Node.NIL is not yet initialized when the constructor is called. Therefore public static Node NIL = new Node(Node.NIL, Node.NIL); is the same as public static Node NIL = new Node(null, null);.

If, on the other hand, NIL was an instance variable (and wasn’t passed as an argument to the Node constructor, since the compiler would have prevented you from passing it to the constructor in that case), it would be initialized every time an instance of Node was created, which would create a new Node instance, whose creation would initialize another NIL instance variable, leading to infinite chain of constructor calls that would end in StackOverflowError.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)