Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

fundamentals

 
Ram Han
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
out put for this below program is 10.can anyone explain this.i saw this quetion in mockexams


public class Honley{
public static int i =60;
public static void main(String argv[]){
Honley h = new Honley();
h.wine();
}
public void wine(){
i = 10;
int i = 20;
System.out.println(this.i);

}
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this case, this is irrelevant because the variable is static.

You are simply printing the value of i in the class Honley.

Instance methods can access static members so you set the value of the static member i to 10, and then when you print this.i, the value of the variable i associated with the class Honley is printed.
 
Pramila Chinguru
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this.i refers to instance variable.
Instance variable i is overridden in wine method to 10, hence 10 is the output.
Incase if you print(i), 20 will be the output. since i represents local variable declared in wine method and has the value of 20.
Hope it helps.
 
Ram Han
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks i got it
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wanted to clarify my last remark.

When a static member of a class is referred to using a qualified instance, then it is irrelevant which instance refers to the static member.

The type of the class is what matters.

You create a local variable named i after you modify the static member i.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic