Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between local variable initialize null and not initialize?

Tags:

java

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.
like image 803
Damith Ganegoda Avatar asked Oct 02 '14 11:10

Damith Ganegoda


3 Answers

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.

like image 199
khelwood Avatar answered Nov 14 '22 02:11

khelwood


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 :(
like image 8
Maroun Avatar answered Nov 14 '22 02:11

Maroun


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/ }

like image 3
marcinj Avatar answered Nov 14 '22 02:11

marcinj