• 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

Can u explain this

 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Sharon...
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i have a doubt, since it i is static, can we change it's value.. wont it give error.
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can not change "static final" variable's value and you can change static variable's value.
 
reply
    Bookmark Topic Watch Topic
  • New Topic