Is it possible to produce undefined behavior when dereferencing `null` in Java?

前端 未结 4 1847
一生所求
一生所求 2021-02-20 03:28

I just learned that dereferencing null in C and C++ can sometimes produce undefined results. This is very intriguing to me, like all bizarre programming behaviors

4条回答
  •  攒了一身酷
    2021-02-20 04:13

    The very concept of a language feature having undefined behaviour is something that the writers of the C and C++ standards use to make it clear that the standard does not require any particular behaviour. This gives the various implementers of C and C++ to do whatever is most efficient or convenient for the particular hardware or operating system the implementation is for. This is because C has always privileged performance over portability. But Java has the opposite priorities; its early slogan was "write once, run anywhere". So the Java language specification does not talk about undefined behaviour, and strives to define the behaviour of all the language features.

    You seem to think that using a null reference could somehow corrupt memory in some circumstances. I think you are confusing C/C++ pointers with Java references. A pointer is essentially a memory address: by casting it to a void * and dereferencing it you have unrestricted ability to corrupt the content of memory. A Java reference is not like a memory address because the garbage collector must be free to move objects to different locations in memory. The translation of a Java reference to a memory address is thetefore something that only the JVM can do; it can never be something that a Java program itself can do. As this translation is entirely controlled by the JVM, the JVM can ensure that the translation is always valid, and always points to the object it ought to and nowhere else.

提交回复
热议问题