aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help needed..... 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 "Help needed....." Watch "Help needed....." New topic
Author

Help needed.....

Mohamed Shafi
Ranch Hand

Joined: Apr 18, 2005
Posts: 119
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.
Lakshmi Prabhakaran
Greenhorn

Joined: Jul 21, 2005
Posts: 4
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.
Rucha Surve
Greenhorn

Joined: Jul 25, 2005
Posts: 1
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help needed.....
 
Similar Threads
Another program. . .
Reg. Reference datatypes in method calls
need help
Passing variables.
Khalid Mock Q - Hide & Seek ??!!