What is difference between :
Object o = null
; and Object o;
(just declaration)Can anyone please answer me?
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.
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.
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.
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.
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 } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With