Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, What is the difference between assigning null to object and just declaration

What is difference between :

  • Object o = null; and
  • Object o; (just declaration)

Can anyone please answer me?

like image 604
김준호 Avatar asked May 07 '13 09:05

김준호


People also ask

What happens when we assign null to object in Java?

If you pass it to a thread to be manipulated, the thread will have a reference to the object until it terminates. In all of these cases, if you set list = null , the references will still be maintained, but they will disappear after these references disappear.

Can we assign null to object in Java?

In Java, null is neither an Object nor a type. It is a special value that we can assign to any reference type variable. We can cast null into any type in which we want, such as string, int, double, etc.

What is difference between null object and object null?

The first two are equivalent, but the "null != object" is an old practice from languages where it is valid to write "if (object = null)" and accidentally assign null to the object. It is a guard to stop this accident from happening.

Can I initialize object with null?

You should initialize your variables at the top of the class or withing a method if it is a method-local variable. You can initialize to null if you expect to have a setter method called to initialize a reference from another class. You can, but IMO you should not do that. Instead, initialize with a non-null value.


2 Answers

It depends on the scope where you declare the variable. For instance, local variables don't have default values in which case you will have to assign null manually, where as in case of instance variables assigning null is redundant since instance variables get default values.

public class Test {     Object propertyObj1;     Object propertyObj2 = null; // assigning null is redundant here as instance vars get default values       public void method() {         Object localVariableObj1;         localVariableObj1.getClass(); // illegal, a compiler error comes up as local vars don't get default values          Object localVariableObj2 = null;         localVariableObj2.getClass(); // no compiler error as localVariableObj2 has been set to null          propertyObj1.getClass(); // no compiler error         propertyObj2.getClass(); // no compiler error     } } 
like image 135
PermGenError Avatar answered Oct 14 '22 05:10

PermGenError


As mentioned, object reference as instance variable need not be assigned null as those take null as default value. But local variables must be initialized otherwise you will get compilation error saying The local variable s may not have been initialized.

For more details you can refer this link

like image 45
Madhusudan Joshi Avatar answered Oct 14 '22 04:10

Madhusudan Joshi