jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusing problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusing problem" Watch "Confusing problem" New topic

Confusing problem

Deepak Kumar Jha

Joined: Feb 07, 2013
Posts: 18

this give an error message that local variable must be initialized.i.e i2
but when we write that code in such a manner

[Formatted and code tags - see UseCodeTags for details]

it does not show any error message . is there any property of final when it used for local variable or something else ..please share your view.
Jenson Joseph

Joined: Feb 06, 2013
Posts: 2
yes, but it again gives error if I change the value of final int i1 = 2;
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Hi Deepak and Jenson. Welcome to the Ranch!

What's happening is that a final int initialised on the same line as it is declared is considered a compile time constant. Therefore the compiler is able to work out that the condition on line 5 is always true. Therefore on line 9 i2 is always initialised.

In the first case i1 isn't a constant. So the compiler can't tell whether the if condition is true or not. So i2 might be initialised, but it might not - and the compiler will complain unless it's absolutely sure.

As Jenson says, if you change i1 to 2 in the second case you'll get an error. Now the compiler knows that i2 won't get initialised.
Deepak Kumar Jha

Joined: Feb 07, 2013
Posts: 18

I understand the solution.

Thanks to @Matthew Brown.
Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 1114
The problem is that the compiler won't initialize i1 and i2 to be 0.

If you have this :

In this case, i1 and i2 are initialized to be 0 by default.
Deepak Kumar Jha

Joined: Feb 07, 2013
Posts: 18

There is no problem with compiler for that question because for local variable compiler never initialize it by default,we have to initialize it before using it. In that question trick associated with constant declaration i.e for final keyword
I agree. Here's the link: http://aspose.com/file-tools
subject: Confusing problem
jQuery in Action, 3rd edition