Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized Object vs Object Initialized to NULL

I'm working in Java.

I commonly setup some objects as such:

public class Foo {     private SomeObject someName;      // do stuff      public void someMethod() {         if (this.someName != null) {             // do some stuff         }     } } 

The question is: Is someName in this example equated to null, as-in I can reliably for all objects assume null-checking uninitialized objects will be accurate?

like image 795
SnakeDoc Avatar asked May 22 '13 18:05

SnakeDoc


People also ask

Are uninitialized objects null?

They are null by default for objects, 0 for numeric values and false for booleans. For variables declared in methods - Java requires them to be initialized. Not initializing them causes a compile time error when they are accessed. What's the reason?

Can we initialize object to null in Java?

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.

Are uninitialized variables null Java?

Java does not have uninitialized variables. Fields of classes and objects that do not have an explicit initializer and elements of arrays are automatically initialized with the default value for their type (false for boolean, 0 for all numerical types, null for all reference types).

Are objects null by default?

Default value of String (or any object) is null, see default value table provided in that link.


1 Answers

Correct, both static and instance members of reference type not explicitly initialized are set to null by Java. The same rule applies to array members.

From the Java Language Specification, section 4.12.5:

Initial Values of Variables

Every variable in a program must have a value before its value is used:

Each class variable, instance variable, or array component is initialized with a default value when it is created

[...] For all reference types, the default value is null.

Note that the above rule excludes local variables: they must be initialized explicitly, otherwise the program will not compile.

like image 118
Sergey Kalinichenko Avatar answered Oct 16 '22 19:10

Sergey Kalinichenko