• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

is this program fine?

 
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
}
}
 
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic