This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
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: 4541

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: 1052
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
Don't get me started about those stupid light bulbs.
subject: Confusing problem
It's not a secret anymore!