What conditions make an instance of an object return null?

Is it possible for the next line to return zero?

MyClass obj = new MyClass(); 

If so, what conditions will cause the null return value?

+4
source share
5 answers

It is not possible to return new to null, assuming that the virtual machine is working correctly.

From section 15.9.4 Java Language Specifications :

The value of the class instance creation expression is a reference to the newly created object of the specified class. Each time an expression is evaluated, a new object is created.

+16
source

No, this cannot return null. However, it may throw an exception, and depending on how you handle this exception, the obj link may still remain empty after the exception has been processed (if you leave a block of code, for example, without catching the exception, the obj link will cease to exist and therefore this irrelevant).

The reasons for exceptions in the constructor are manifold, for example, if you run out of memory (in this case you get an OutOfMemoryError ), or if you access an uninitialized field that is still null and will NullPointerException .

+6
source

static initializer error

as

 public class MyClass { static { throw new Error("Error"); } } public class MyClass2 { static MyClass test=new MyClass(); } 

You cannot ask your question without specifying a context. On the application server above, Myclass2 with test = null will be displayed. What for? Because the error is usually delayed by the application server.

+3
source

The short answer is NO.

But you can throw an exception from the constructor, in which case, if obj was originally set to null , it will remain null .

+1
source

In my opinion, this is not possible. If somehow you run out of memory in Java, you will get an OutOfMemoryError exception.

0
source

Source: https://habr.com/ru/post/1395311/


All Articles