1/03/2007

Variable might not have been initialized

In Java, class instance variables and static variables have default values: null for all object types, false for boolean primitive and 0 for numeric primitives. But local variables inside a method have no defaults.

Consider the following code snippet:

public static void main(String[] args){
java.util.Date d;
System.out.println(d);
}
It will fail to compile with this error:
variable d might not have been initialized
System.out.println(d);
1 error
However, the following will compile and run successfully:
public static void main(String[] args){
java.util.Date d;
}
Because the rule is that all local variables must be initialized before they are first read. So it's perfectly OK to first declare a local variable without initializing it, initialize it later, and then use it:
public static void main(String[] args){
java.util.Date d;
//do more work
d = new java.util.Date();
System.out.println(d);
}
It may be an old habit from languages like C, where you need to declare all local variables at the beginning of a code block. But in Java with this rule in place, it's best to defer declaring local variables till needed.

30 comments:

Anonymous said...

well this rule is most frustrating when trying to close a resource in a finally block. if I instantiate the resource inside a try, but try to close it within the finally, I get this error. if I move the instantiation outside the try, I get another error stating that a it must be within a try.

very frustrating.

Anonymous said...

Thanks for posting this! I searched on google and this page was the first result, very good to know!

Unknown said...

If I am declaring PI, how about that,
Do I have to specifically mention the value of PI(If so then wt the hell is this error) which I am getting for PI

Anonymous said...

Sometimes when you use for, while, etc. to initialize you need to use for example:
variable1 = null;
That message will dissapear.

Anonymous said...

Thanks! About 1 hour trying to find out... and in one minute you saved me.

Eric W said...

Thank you, that was very helpful! :D

Eric W said...
This comment has been removed by the author.
Anonymous said...

master

Bill said...

This is actually a huge feature of Java, and you should absolutely get out of the habit of typing "=0" or "=null" when declaring variables.

This uses branch code checking to ensure that every possible path that could get to the use of a given variable has, at some point, initialized that variable.

If you go around setting them to 0, you will eliminate this extremely useful warning. If you are getting the warning, look at it closely to figure out if you are missing something. Sometimes you still have to initialize it, but now I never do until I'm sure that's the best way to code it.

Arla said...

I wrote the following code to set a variable to an unused, random value:

// Find an empty place in tmp
boolean foundEmptyPlace = false;
while (!foundEmptyPlace) {
randomNumber = randomGenerator.nextInt(tmp.length);
if (tmp[randomNumber] == null) {
foundEmptyPlace = true;
}
}
// do something with tmp[randomNumber]

Here I get the "might not have been initialized" error, though reasonably it must have been initialized within the while loop. My solution was to initialize randomNumber (= 0) before the loop. But, as Bill points out, this seems to be an unpreferrable habit. Can I avoid the error in a more clean and correct way?

Unknown said...

i am getting error in following
System.out.println(num[j]);
what should i dooooo??????

Unknown said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Course in Chennai

Java Online Training India

Dipanwita said...

Very useful blog. java training in chennai

franklinraj said...

Thank you for excellent article.

Please refer below if you are looking for best project center in coimbatore

soft skill training in coimbatore
final year projects in coimbatore
Spoken English Training in coimbatore
final year projects for CSE in coimbatore
final year projects for IT in coimbatore
final year projects for ECE in coimbatore
final year projects for EEE in coimbatore
final year projects for Mechanical in coimbatore
final year projects for Instrumentation in coimbatore

jvimala said...

Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.
Java Training in Chennai | J2EE Training in Chennai | Advanced Java Training in Chennai | Core Java Training in Chennai | Java Training institute in Chennai

gokul said...

Thank you for this informative blog
data science interview questions pdf
data science interview questions online
data science job interview questions and answers
data science interview questions and answers pdf online
frequently asked datascience interview questions
top 50 interview questions for data science
data science interview questions for freshers
data science interview questions
data science interview questions for beginners
data science interview questions and answers pdf
data science interview questions for experienced
top 100 data science interview questions

Elevators and Lifts said...

NIce post... The information you shared was so awesome. elevators and lifts | home lifts | Lifts for home | Residnetial lifts

Anonymous said...


Thanks for sharing the valuable information here. So i think i got some useful information with this content. Thank you and please keep update like this informative details.


erp software development company in us
erp software company in us
list of erp software companies in us
erp in chennai
list of erp software companies in chennai
Latest CRM Software

Aravinth said...

Nice article, interesting to read…
Thanks for sharing the useful information

tasty catering services in chennai
best caterers in chennai
catering services in chennai
tasty catering services in chennai
veg Catering services in chennai

Savanah Eden said...

We help you to get high traffic for your websites using latest ethics,visit us
Linkedin Marketing company chennai
Erp software development company in chennai
seo company in chennai
Web portal development company in chennai

Rajesh said...

Nice infromation
Selenium Training In Chennai
Selenium course in chennai
Selenium Training
Selenium Training institute In Chennai
Best Selenium Training in chennai
Selenium Training In Chennai

Rajesh said...

Rpa Training in Chennai
Rpa Course in Chennai
Rpa training institute in Chennai
Best Rpa Course in Chennai
uipath Training in Chennai
Blue prism training in Chennai

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Training institute In Chennai
Best Data Science Training In Chennai

Rajesh said...

Python Training In Chennai
Python course In Chennai
Protractor Training in Chennai
jmeter training in chennai
Loadrunner training in chennai

Advanced Diploma in Embedded Systems said...

thanks for sharing this nice infoamtion..i really enjoyed to read your information.learn bench india is the best project center in chennai..
to know more about this best project center in chennai
best final year project center in chennai
best final year ieee project center in chennai
best embedded project center in chennai

Shruti said...

This website was... how do you say it? Relevant!! Finally I have found something which helped me. Thank you!
Selenium Courses in Marathahalli

selenium institutes in Marathahalli

selenium training in Bangalore

Selenium Courses in Bangalore

best selenium training institute in Bangalore

selenium training institute in Bangalore




Shivani said...

You need to take part in a contest for one of the greatest sites on the web. I am going to highly recommend this website!


Best Advanced Java Training In Bangalore Marathahalli

Advanced Java Courses In Bangalore Marathahalli

Advanced Java Training in Bangalore Marathahalli

Advanced Java Training Center In Bangalore

Advanced Java Institute In Marathahalli

Infocampus said...

It’s hard to come by experienced people about this subject, but you seem like you know what you’re talking about! Thanks.
Java Training in Bangalore
Python Training In Bangalore

Elevators and Lifts said...

Great Post. Home elevators Melbourne
Home lifts

Infocampus said...

It’s hard to come by experienced people about this subject, but you seem like you know what you’re talking about! Thanks.
Java Training in Bangalore
Python Training In Bangalore

Faizal said...

It's Pleasant to Visit your site, Such a Informative Articles Are Really Interesting.Keep Blogging...
Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery