Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When Must Local Variables Be Initialized?

 
Mike Kelly
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mike Kelly
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Corey for clearing up that loose end.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic