This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Variable scope & life time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable scope & life time" Watch "Variable scope & life time" New topic
Author

Variable scope & life time

Dimuthu Lakmal
Greenhorn

Joined: Nov 03, 2012
Posts: 8

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

Joined: Oct 13, 2005
Posts: 39079
    
  23
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

Joined: Oct 13, 2005
Posts: 39079
    
  23
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Nov 03, 2012
Posts: 8

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...
 
GeeCON Prague 2014
 
subject: Variable scope & life time