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?
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?
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.
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).
Default value of String (or any object) is null, see default value table provided in that link.
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.
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