| Author |
Initializing reference variable
|
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
this does not compile but this compiles. How does assigning null to abc make the code compilable ? What is the difference between declaring String abc and String abc=null ?
|
Regards,<br />Arnab
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16816
|
|
In Java, local variables must be initialized. The compiler will complain when they are not. And BTW, just because a program compiles does not mean that it is correct. If you run the program, it should throw a null pointer exception, as soon as it tries to use the variable. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
Hi Henry, That's right. Since "abc" is a local varibale, it must be initialized. hence the first code shows a compilation error while the 2nd code does not as it is assigned with a null value. My question is since in the first code, "abc" is not initialized, doesn't it mean that "abc" points to null ? If that is true then the 2nd code should not compile as well as "abc" still points to null. Right ?
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
Originally posted by Arnb Sen: Hi Henry, That's right. Since "abc" is a local varibale, it must be initialized. hence the first code shows a compilation error while the 2nd code does not as it is assigned with a null value. My question is since in the first code, "abc" is not initialized, doesn't it mean that "abc" points to null ? If that is true then the 2nd code should not compile as well as "abc" still points to null. Right ?
No, abc does not "point to null" in the first version because it is uninitialized. When you declare a local variable, the compiler will allocate some space in memory for it. However, this location in memory already has some data in it from the last time it was used. If Java allowed the code in your first example, then it would use this unknown value as the reference. This uknown value could be pointing to a supposed object just about anywhere in memory. Can you see why this is bad? So, abc will point to null, only if you explictly say so as in your second example. Layne
|
Java API Documentation
The Java Tutorial
|
 |
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
|
ok understood.. so if abc points to null, JVM removes the unknown data and replaces it with a null object. 'abc" then points to this null object. Right ?
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
|
Not a null object -- null means precisely "no object at all." And "no object" is quite different from "some random value."
|
[Jess in Action][AskingGoodQuestions]
|
 |
Arnb Sen
Ranch Hand
Joined: Feb 23, 2004
Posts: 145
|
|
|
I see.. understood.. so that is why one code compiles while the other does not.
|
 |
 |
|
|
subject: Initializing reference variable
|
|
|