File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes variable not initialed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "variable not initialed" Watch "variable not initialed" New topic

variable not initialed

Vijay Bhuruk
Ranch Hand

Joined: Feb 28, 2008
Posts: 31

when i compile,get error. Error: variable b might not have been initialised.

only way to clear error is initialise b.(tested for b=4)

but when i tried below code,where i have not initialised variable b,it works too.


James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 580

Try this it will still give error...

The reason the first code gives error is.....
"a" is non-final varible means it can change its value later....
And the compiler know that if the if condition fails "b" will not be initilaized.So error says "using before initilzing"

In the second case "a" in final and compiler can be sure that the value will not change and the "b" variable WILL be initialized

Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Vijay Bhuruk
Ranch Hand

Joined: Feb 28, 2008
Posts: 31

Thanks James.
harilal ithikkat
Ranch Hand

Joined: Oct 06, 2008
Posts: 221
James really cool answer.....................

SCJP 1.5
"A candle looses nothing by lighting another candle"
Monu Tripathi

Joined: Oct 12, 2008
Posts: 1369

Just adding my 25 paise..

If interested in this idiosyncrasy of the Java compiler, you might want to read JLS Chapter 16 - Definite Assignment which addresses this area.

[List of FAQs] | [Android FAQ] | [Samuh Varta]
I agree. Here's the link:
subject: variable not initialed
jQuery in Action, 3rd edition