wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can u explain this Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Can u explain this" Watch "Can u explain this" New topic

Can u explain this

Supriya Nimakuri
Ranch Hand

Joined: May 23, 2006
Posts: 83
public class Honley{
public static int i =99;
public static void main(String argv[]){
Honley h = new Honley();
public void wine(){
i = 10;
int i = 20;


The output is : Compile and prints 10.

I thought it would print 20..can anyone explains why it prints 10
Sharn Arora
Ranch Hand

Joined: May 09, 2006
Posts: 57
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

SCJP 1.4 - 95%
Supriya Nimakuri
Ranch Hand

Joined: May 23, 2006
Posts: 83
Thanks Sharon...
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
vinod balaji
Ranch Hand

Joined: May 18, 2006
Posts: 84
i have a doubt, since it i is static, can we change it's value.. wont it give error.
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
You can not change "static final" variable's value and you can change static variable's value.
Don't get me started about those stupid light bulbs.
subject: Can u explain this
It's not a secret anymore!