In Java, what is the difference and best way to do?
Integer x = null; // x later assign some value.
Integer y; // y later initialize and use it.
Local variables must be assigned to something before they are used.
Integer x = null;
myFunction(x);
// myFunction is called with the argument null
Integer y;
myFunction(y);
// This will not compile because the variable has not been initialised
Class variables are always initialised to a default value (null
for object types, something like zero for primitives) if you don't explicitly initialise them. Local variables are not implicitly initialised.
The answer depends on what type of variable are you referring.
For class variables, there's no difference, see the JLS - 4.12.5. Initial Values of Variables:
... Every variable in a program must have a value before its value is used:
For all reference types (§4.3), the default value is
null
.
Meaning, there is no difference, the later is implicitly set to null
.
If the variables are local, they must be assigned before you pass them to a method:
myMethod(x); //will compile :)
myMethod(y) //won't compile :(
Its better to not set it to null, otherwise you can by accident use it and cause NPE. Compiler wont help you with compile error. Only set to null if you want to have logic like if ( x != null ) { /use it/ }
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