• 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

Help needed.....

 
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
code
----------------------------------------

public class kha8 {
int a;
int b;
public void f() {
a = 0;
b = 0;
int[] c = { 0 };
g(b, c);
System.out.println(a + " " + b + " " + c[0] + " ");
}
public void g(int b, int[] c) {
a = 1;
b = 1;
c[0] = 1;
}
public static void main(String[] args) {
kha8 obj = new kha8();
obj.f();
}
}

what will be the output?

a.000
b.001
c.010
d.100
e.101

ans-e.

----------------------

can anyone explain why b's value's is 0 and a's value is retained to 1???


Thanks,

Shafi.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi


In method g(int b, int[] c) b refered here is the local variable whereas a is the instance variable. To access a instance variable use this.variableName (this.b) where there is a local variable in the same name.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,


In the above code, when the method g() is invoked, it is passed instance variable b and array c[]. In the method g() itself there are local variables with the same names as the instance variables b & c[]. so, when you are setting b = 0, you are actually changing the local variable and not the instance variable. But variable a in the method g() is not local coz it has not been declared locally, so when u set "a" to 0 , you are actually changing the instance variable. So the result will be 101.
 
reply
    Bookmark Topic Watch Topic
  • New Topic