• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Variable shadowing

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Inst{
protected int myst;
public void go(int myst){
System.out.println(myst); //1
myst=myst; //2
}
public static void main(String args[])
{
Inst a=new Inst();
a.go(5);
System.out.println(a.myst);
}
}

Why the o/p s 5 0.
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Why the o/p s 5 0.



Because local variable takes precedence of instance variable.

In this line (System.out.println(myst); //1
it prints local variable myst....so it prints 5

myst=myst; //2
in this line local variable is assign to itself
....if you want to assign to instance variable use this(this.myst=myst)


in this line System.out.println(a.myst);
it prints instance variable with default value 0

Hope you clear now
reply
    Bookmark Topic Watch Topic
  • New Topic