Java null behavior
I'm trying to understand how null works in Java
If we assign null to any object, what happens after the scene? Does it allocate memory location addresses that point to empty "objects" or other content?
I've tried the following program and I've learned that all nulls point to the same location
But can someone tell me how Java raises NullPointerException and how null in Java works?
class Animal{ } class Dog{ } public class testItClass { public static void main(String args[]){ Animal animal=null; Dog dog=null; if(((Object)dog) == ((Object)animal)) System.out.println("Equal"); } }
yield
be equal to.
Solution
A distinction should be made between references and objects You can assign null to the reference Objects are usually created in the heap using new operators It returns a reference to an object
A a = new A();
Objects of type A are created in the heap You are given reference A. if you assign now
a = null;
The object itself still resides in the heap, but you will not be able to access it using reference a
Note that the object may be garbage collected later
UPD:
I have created this class to see its bytecode (give it to me for the first time):
public class NullTest { public static void main (String[] args) { Object o = new Object(); o = null; o.notifyAll(); } }
It produces:
C:\Users\Nikolay\workspace\TestNull\bin>javap -c NullTest.class Compiled from "NullTest.java" public class NullTest { public Nulltest(); Code: 0: aload_0 1: invokespecial #8 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: new #3 // class java/lang/Object 3: dup 4: invokespecial #8 // Method java/lang/Object."<init>":()V 7: astore_1 8: aconst_null 9: astore_1 10: aload_1 11: invokevirtual #16 // Method java/lang/Object.notifyAll:()V 14: return }
You can see the result of setting null to the reference:
8: aconst_null 9: astore_1
List of byte code instructions
Basically, it puts the value of the value at the top of the stack and saves it to the reference But this mechanism and reference implementation are internal to the JVM
How is reference to java object is implemented?