File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Help needed.....

Mohamed Shafi
Ranch Hand

Joined: Apr 18, 2005
Posts: 119

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();

what will be the output?




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


Lakshmi Prabhakaran

Joined: Jul 21, 2005
Posts: 4

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

Joined: Jul 25, 2005
Posts: 1

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:
subject: Help needed.....
It's not a secret anymore!