wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Local variable might have not been initialized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Local variable might have not been initialized" Watch "Local variable might have not been initialized" New topic
Author

Local variable might have not been initialized

Faber Siagian
Ranch Hand

Joined: Jul 08, 2008
Posts: 52
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 ?


Sun Certified Programmer for the Java 2 Platform, Standard Edition 5.0 (88 %)
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3816

anyway x get initialized(under the specified condition "if else block"). So compiler won't complain.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Faber Siagian
Ranch Hand

Joined: Jul 08, 2008
Posts: 52
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

Joined: Sep 24, 2007
Posts: 19
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-



~Sumit<br /><a href="http://faq.javaranch.com/view?ScjpWallOfFame" target="_blank" rel="nofollow">SCJP Wall of Fame</a>
Faber Siagian
Ranch Hand

Joined: Jul 08, 2008
Posts: 52
Ok i get it now. Thanks to all for explaining.
doug rosenberg
Greenhorn

Joined: Oct 31, 2007
Posts: 29
Actually it compiles and runs just fine for me.
It depends upon how smart your compiler is (JDK 1.6.03)


SJCP 6.0
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Local variable might have not been initialized
 
Similar Threads
Local variable scope
array question
Local variable initialization-Its magic
What Compiler can tell and can't tell
Why is this thread closed?