aspose file tools*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "variable not initialed" Watch "variable not initialed" New topic
Author

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.



why?

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

SCJP 6
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"
itechmentors.com
Monu Tripathi
Rancher

Joined: Oct 12, 2008
Posts: 1369
    
    1

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: http://aspose.com/file-tools
 
subject: variable not initialed