GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes When Must Local Variables Be Initialized? 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 "When Must Local Variables Be Initialized?" Watch "When Must Local Variables Be Initialized?" New topic
Author

When Must Local Variables Be Initialized?

Mike Kelly
Ranch Hand

Joined: Jul 18, 2001
Posts: 78
The following code compiles fine. I would like to know why variable c, a local variable, is not explicitly initililized? Do local variables need to be initilized immediately or just before use in an expression? Thanks.
public class TestClass
{
static int a;
int b;
public TestClass()
{
int c;
c = a;
a++;
b += c;
}
public static void main(String args[]) { new TestClass(); }
}
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Local variables must be initialized prior to their values being used. The following is legal:

while the following is illegal:

By assigning a to c, as you did, you initialized c. It doesn't need to be initialized immediately, just prior to its value being used in an expression.
I hope that helps,
Corey


SCJP Tipline, etc.
Mike Kelly
Ranch Hand

Joined: Jul 18, 2001
Posts: 78
Thanks Corey for clearing up that loose end.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When Must Local Variables Be Initialized?