?
Solved

Initialization of local reference variable

Posted on 2006-05-03
34
Medium Priority
?
488 Views
Last Modified: 2012-06-27
In a java class if you have not initialize a local reference variable before using it, the compiler throws exception.
But when you explicitly initialize it with null it didn't complain. Why is it so? What is the advantage of this behavior as still if we wants to use that reference variable we get NullPointerException?
0
Comment
Question by:gksinghiet
  • 9
  • 6
  • 6
  • +3
30 Comments
 
LVL 24

Accepted Solution

by:
sciuriware earned 200 total points
ID: 16603229
That's not true: the exception is ALWAYS thrown when it's null and you are using it as initialised.

The compiler(s) may warn you that you forgot to initialise it.

;JOOP!
0
 
LVL 92

Assisted Solution

by:objects
objects earned 200 total points
ID: 16603245
Because all local vars *must* be explicitly initialized before being used. What it is initialized to is irrelevant in this respect.
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 16603247
In fact this is a very old problem (back in the 1950's):
how could the compiler predict that, somehow, a variable will get a proper value in the long run?

All a compiler can do is warn you that code might be missing.

A good reason to start to use an IDE like ECLIPSE: it is smarter and warns you that
a variable SOMETIMES (conditional) will not have a proper value.

;JOOP!
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 3

Assisted Solution

by:arun_kuttz
arun_kuttz earned 200 total points
ID: 16603254
Actually this is done to promote good programming practice :
Declaring local variables without using them immediately will unnecessarily increase their scope. This decreases legibility, and increases the likelihood of error.

here is a good article on the same :
http://www.javapractices.com/Topic126.cjp

-KuTtZ
0
 
LVL 5

Author Comment

by:gksinghiet
ID: 16603366
>>Because all local vars *must* be explicitly initialized before being used...
Yes this constraint is enforced by java compiler but I want to know the advantage of enforcing this.
>>how could the compiler predict that, somehow, a variable will get a proper value in the long run
Just by checking its reference value where the variable is used. Like one did in his code as: if (ref == null){}
>>Actually this is done to promote good programming practice
Yes you are right that declaring local variable immediately before using mitigates the chances of error but my question is that by allowing a reference variable to be declaring with null value what are we achieving?
0
 
LVL 5

Author Comment

by:gksinghiet
ID: 16603405
>>Just by checking its reference value where the variable is used. Like one did in his code as: if (ref == null){}
Sorry it is not that easy, as at runtime the value might change. But still it dosn't answers my question because then the compiler should allow the reference variable to be used with being initialized instead of initializing it with null.
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 16603484
>>>  the compiler should allow the reference variable to be used with being initialized instead of initializing it with null.
That's the point! How would you check if a reference is valid if you could not compare it to null?

;JOOP!
0
 
LVL 5

Author Comment

by:gksinghiet
ID: 16604012
>>That's the point! How would you check if a reference is valid if you could not compare it to null?
But at the time of initialization compiler can check for the null reference. Isn't it?
0
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 200 total points
ID: 16604141
It doesn't check for null reference. It just checks if you have initialized it or not. If it is not initialized, like:

String a ;

If you use 'a' anywhere in the program without assigning using a = something ; it will give you an error.
0
 
LVL 3

Expert Comment

by:arun_kuttz
ID: 16604292
In Java, Class and Instance variables need not be explicitly initialized with anything... The compiler automatically assigns an initial value.
I guess the point of ur contention is y Local variables are treated differently and since the compiler already goes to the trouble of assigning initial values for non-local variable, y not just go ahead and provide initial values to local-variables.. right ??

well.. my take on the whole thing is that class and instance variables are required to maintain the state of an object, its is expected to keep changing over the life time of the program and therefore has a scope = lifetime of the object, Thus initial values are not really important, its just the value at any point of time thats significant..

on the other hand, Local variables are to be used within methods and are not supposed to be used to record state, its supposed to be used as temporary objects. The JVM architecture states that Java initializes something called a "Method area". Althought this method area is created on the heap, the initial size is probably calculated and optimized based on how local variables are initialized..

-KuTtZ
0
 
LVL 3

Expert Comment

by:arun_kuttz
ID: 16604382
check out the VM specs

http://java.sun.com/docs/books/vmspec/2nd-edition/html/Overview.doc.html

espescially section 3.5 and 3.6.
Apparantly Local Variables ARE allocated on a Stack (which can be made expandable). which could be the reason y u have to explicitly initialize Local Variables...

-KuTtZ
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16604489
>> Class and Instance variables need not be explicitly initialized with anything... The compiler automatically assigns an initial value.

Yes, but if you use it without initializing, it is likely to give an error. Like:

String a ;
String b = a.trim () ; // will give a compilation error that 'a' might not have been initialized
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16604514
However, if it is used somewhere else, it might not give an error but might just throw an exception upon usage. Like:

public class Test
{
  private String a ;
  public String getA ()
  {
    return a ; // no compilation error here
  }
}

Test obj = new Test () ;
String c = obj.getA ().trim () ; // will throw NullPointerException
0
 
LVL 3

Expert Comment

by:arun_kuttz
ID: 16604614
> String a ;
> String b = a.trim () ; // will give a compilation error that 'a' might not have been initialized

will definitely NOT give a compilation error... it will only throw a Runtime NullPointerException.
as the compiler DOES initialize it to null..

-KuTtZ
0
 
LVL 3

Expert Comment

by:arun_kuttz
ID: 16604620
i mean.. if String a is an Instance/Class cariable... that is

-KuTtZ
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16604627
>> will definitely NOT give a compilation error... it will only throw a Runtime NullPointerException

It WILL give a compile time error if it is local to a method.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16604633
>> if String a is an Instance/Class cariable... that is
>> as the compiler DOES initialize it to null..

Yes, in that case it will throw an exception because you are defining it somewhere else and using it somewhere else, like in http:#16604514
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 16604986
Well what's the use of this discussion sofar?
Did we learn something?

;JOOP!
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16605041
From the earlier comments, the asker still did not had it clear: >> But at the time of initialization compiler can check for the null reference. Isn't it?

Hopefully some more explanation will help him understand in which cases it will throw an exception and in which cases it will generate a compile-time error.
0
 
LVL 5

Author Comment

by:gksinghiet
ID: 16605312
>> check out the VM specs
I will go through the spec and then come back to the discussion.
Actually I know when the compiler complains and when it will not.
But I have a curiosity that why the language implementers have putted in such constraint.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16605347
>> But I have a curiosity that why the language implementers have putted in such constraint.

It is good. Whenever it can warn you of potential errors, it does. Because it knows that if you use an uninitialized variable by calling a method on it, it will throw an Exception. So wherever possible, it tries to save you from doing that. I only see something positive there. What negative do you see? You don't want your code to thrown an exception.
0
 
LVL 5

Author Comment

by:gksinghiet
ID: 16605511
>> I only see something positive there.
I couldn't see any thing positive or negative.
Take for example that if JVM allows a local refernce variable to be used without initializing it then it will set it with a default value null as in case of instance or class variables. And ultimately by allowing a local reference variable to be initialize with null it is still doing the same.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16605590
>> And ultimately by allowing a local reference variable to be initialize with null it is still doing the same.

No, you need not initialize it with a nul alwaysl. You can initialize it with something else. For example, in:

String a = "Hello" ;
int i = a.length () ;

At least by forcing you to explicitly initialize it with something, it is making sure tha you are aware of what value you are using to initialize it and therefore if any exception still happens after that, it is forced by your value (e.g., if you still initialize it to null and call length () on it, it is helpless - it has to throw). But it makes sure *you did not forget to initialize it by mistake*, in case you intended to initialize it with something relevant (not necessarily null).
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 16605659
In some exception-handling scenarios also, it is helpful (when resources have to be released in finally blocks):

FileInputStream fis = null ; // initialize, to avoid compile-time error in finally block
try
{
  fis = new FileInputStream ( .... ) ;
  // read data from the file
}
catch ( Exception e )
{
  e.printStackTrace () ;
}
finally
{
  if ( fis != null ) // if we had not initialized it outside the try block, this would give an error
    fis.close () ;
}

In this kind of a case, initializing it to null is sufficient because later we are making sure we call methods on it only if it has a non-null value so there will not be run-time exceptions. The null initialization is to get rid of the compile-time error because we choose to close it in the finally block and not the try block as a good programming practice (since finally will be executed even if there is some I/O exception in the try block, in between). If we had wanted to close it in the try block itself as a bad programming practice, we wouldn't have needed to initialize it to null outside, because inside the try block it is anyway initialized to a new object.
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 16606346
gksinghiet, by now you know how it works.
If you really want to know why, contact the SUN people:
you will be surprised, embarrased and you will still not understand why.
Many of us tried that once.

Try to use it. It's a fact of (JAVA) life now.

;JOOP!
0
 
LVL 19

Assisted Solution

by:Jim Cakalic
Jim Cakalic earned 200 total points
ID: 16616666
As has been mentioned previously Java class and instance fields are automatically initialized whereas local variables are not but the compiler performs simple flow analysis to be sure that an assignment occurs before any access. While the dichotomoy might seem strange, I consider the two seemingly incompatible (or at least different) initialization strategies to be a product of the same analysis of program safety vs. performance.

Uninitialized data is a common source of defects in programs written in languages like C. Java helps to prevent some uninitialized data problems automatically by guaranteeing fields of loaded classes and newly constructed objects will be initialized to a specification-defined state. This ensures a reliable consistent initial state on which your code can depend. Since Java objects are allocated from a JVM common heap, it also ensures that data left over in memory reclaimed from a previously garbage-collected object cannot be read by a malicious new object. That could be a potentially serious security violation.

Why wouldn't Java provide similar initialization guarantees for local variables? I think the answer, in part at least, is because initialization is not free. On the object side, we have concerns of security/privacy as well as program safety. The security/privacy concerns aren't as relevant on the local variable side because these are allocated off a thread-private stack. (And the compiler's refusal to generate bytecode when you don't initialize is another hedge.) But we still have issues of program safety. So what do you think the typical ratio of objects constructed to method calls performed is during the life/run of a particular application? I'm just spitballing here, but I would expect method invocation to be at least several times more frequent than object construction. Maybe even an order of magnitude or more. If Java were to guarantee local variable initialization then each time a method was called and a new stack frame was allocated, the JVM would have to initialize the memory for the local variables. That isn't free. And the method is likely to initialize the variables itself anyway so the effort would be wasted.

So I think the balance point was tipped in favor of performance when it came to local variable initialization. Objects must be initialized because of security concerns and it provides a solid guarantee of starting object state. Since developers generally try to optimize (aka reduce) object construction the cost of providing the initialization at run time is lowered. But developers typically try to reduce method invocation. Actually, the opposite is the case as refactoring techniques encourage composing larger methods from smaller methods. We all turn up our noses at the 30, 50, 100+ line methods, right? So the cost of initializing stack frames on each method invocation goes up as good development techniques are applied. Better to eat the cost of static flow analysis at compile time and warn of possible uninitialized variables than to incur the much larger run time cost of default initialization.

But that's just my opinion. I might be wrong.

Regards,
Jim
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 16616913
Last paragraph I mean to type, "developers /don't/ typically try to reduce method invocation." :-(
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 16885968
OK
0
 
LVL 5

Author Comment

by:gksinghiet
ID: 16891893
I found myself confused in deciding whom to give points and whom not to give, as all inputs are valued for me.
So I leave this responsibility to Administrator.
But I definitely like to thanks all experts for there valued inputs. Thanks a lot :-)
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 17230005
yep
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month17 days, 10 hours left to enroll

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question