Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a variable assigned to null and others not assigned

Tags:

java

what is the difference between a variable assigned to null and others not assigned in java.

I know that there is a difference in the method's block , witch mean i can use the variable that has initialised to null but i can't use that isn't initialised

can you tell me why ?

edit: Thanks to everyone who answered

My question is about the behavior and the form of references in the memory

like image 868
ahmed S Avatar asked Apr 02 '15 13:04

ahmed S


3 Answers

What is the difference between a variable assigned to null and others not assigned?

  • An uninitialized variable does not have a value, not even null (which is why it can't be read)
  • An initialized variable does have a value (for instance null, 5 or "hello").

Note that member variables get default values assigned to them automatically (and the default value for a reference type is null). So while it may seem like you can read an "uninitialized" member variable, the truth is that it is in fact initialized.

like image 67
aioobe Avatar answered Nov 14 '22 22:11

aioobe


It's explicit intent versus implication. If you don't set an object to anything you may have forgotten and thus the compiler reminds you. If you explicitly set to null, then the compiler is confident you made the choice. Also, for some types, the unset value could be something other than null, so allowing the compiler to make the choice is dangerous (c.f. C++ defaulting issues differing between implementations).

like image 44
Jeff Watkins Avatar answered Nov 14 '22 22:11

Jeff Watkins


Variables assigned to null means it is not pointing to anything where as the one which is not assigned and if it is a local variable means it is not even initialized yet

Test t1=null; ----> Not Pointing to any Object 
Test t2; ------> Not even initialized 

if t2 is local variable and you will use it you'll get Compilation Error, as first initialize before use as default value is not there for this variable

like image 26
Neeraj Jain Avatar answered Nov 14 '22 23:11

Neeraj Jain