Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can u explain this

 
Supriya Nimakuri
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Honley{
public static int i =99;
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);

}
}


The output is : Compile and prints 10.

I thought it would print 20..can anyone explains why it prints 10
 
Sharn Arora
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
keyword 'this' refers to the current instance of the object.
In the given program, you are printing this.i which refers to 'i' which is the member variable of the class and not local variable of the method. Hence, the output is 10 as the value of i is changed from 99 to 10 in the method.
Also note, theres an implicit 'this' in statement i = 10
Read i=10 as this.i = 10
 
Supriya Nimakuri
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Sharon...
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no instance variable i in this class. The code is referencing a static variable through the this reference which is equivalent to referencing the variable as Honley.i
 
vinod balaji
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have a doubt, since it i is static, can we change it's value.. wont it give error.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can not change "static final" variable's value and you can change static variable's value.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic