• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusing problem

 
Deepak Kumar Jha
Greenhorn
Posts: 18
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, but it again gives error if I change the value of final int i1 = 2;
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 18
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand the solution.

Thanks to @Matthew Brown.
 
Himai Minh
Ranch Hand
Posts: 1256
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 18
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic