Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable scope & life time

 
Dimuthu Lakmal
Greenhorn
Posts: 8
Android Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi..I'm an extremely amateur to JavaRanch & i need a big help...
Why the following first one can be compiled & second one can't be compiled?
1)


2)

p.s-The second program can be compiled by moving 'System.out.println(y);' to inside of the block of if statement...
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

It is not a case of scope of the variable, but whether it has a value. In the case of fields, they have a default value, but local variables do not have default values. If you have that print statement inside the if block, then you can be sure that the variable will have a definite value when the print statement is reached.
If the print statement is outside the if, what happens when the if is not called? You would try to print something without a definite value, and the compiler won’t permit that.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You appear to have missed the code button; I have edited your post and you can see how mcuh better it looks don’t sue tabs for indenting; use spaces.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference between the two cases is that this makes x a compile-time constant:


while this does not:


When x is a constant, the compiler knows that if (x > 100) is if (1000 > 100) which is of course if (true), so it just gets rid of the if altogether and unconditionally executes the y = -1; line. This means that when it gets to the println() call, it knows that y has been given a value.

When x is not a constant, it doesn't know whether the if block will execute, so it doesn't know whether y will have a value when we try to print it.
 
Dimuthu Lakmal
Greenhorn
Posts: 8
Android Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You appear to have missed the code button; I have edited your post and you can see how mcuh better it looks don’t sue tabs for indenting; use spaces.

I got that sir ...i used geany to compile & i just copied & pasted it...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic