• Post Reply Bookmark Topic Watch Topic
  • New Topic

is this program fine?  RSS feed

 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Temp {

public static void main(String args[]) {

int x;
x=10;
if(x==10)
{
int y=20;

System.out.println("x is " +x);
System.out.println("y is " +y);
x=y*20;
}

System.out.println("x is" +x);

/***************************doubt****************/
IN the above line x should print 10 since x=y*20 value should be retained in the block only ,but when i run this program i get x=40 ?? can anyone tell why?
}
}
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, the result of x=y*20; will be retained because you are assigning the result to a vairable that is in scope for the scope of the method.
If you tried to print out the value of y (in your last print statement) you would get a compilor error, as y is no longer in scope, because it has block level scope for the block it was decalred in.
 
Jaime M. Tovar
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable scope was defined when the variable was declared, not when it was used.
[ August 31, 2007: Message edited by: Jaime Tovar ]
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy, the scope of int x is the whole main method. You can see it better when the code is indented:

scope of x in italics.



Bu.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!