• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Local variable might have not been initialized

 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code is one of SCJP 6 mock exams contributed by Cameron Wallace McKenzie
and posted in this forum with subject "Some Runtime vs. Compile Time SCJP 6.0 Mock Exam Questions".



I expect the compiler error at line 7, saying that x might have not been initialized, but it is not.
If i remove line 7 out of the loop block, the compiler error.

This is really confusing. What is the difference of putting the System.out.print(x); inside or outside
the loop block ?
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
anyway x get initialized(under the specified condition "if else block"). So compiler won't complain.
 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Vijitha,

As you said that x gets initialized inside the "if-else", why the compiler still complains even if I put System.out.print(x); out of the loop ?
 
Sumit Gaikaiwari
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Faber,

The reason compiler complains is because for loop is also conditional, it may not run even single time if condition does not satisfies for first time only...

If you change loop such that it will definitely run and x will get value, compiler wont complain. Try following code-

 
Faber Siagian
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok i get it now. Thanks to all for explaining.
 
doug rosenberg
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually it compiles and runs just fine for me.
It depends upon how smart your compiler is (JDK 1.6.03)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic