John specter
John specter

Reputation: 171

Unexpected result of java calculations

As a result of the following snipet, i got "1 0 1", but i don't know why, im expecting "1 1 1" as a result. please can anyone explain to me how things go arround

public class Qcb90 {
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) {
    Qcb90 obj = new Qcb90();
    obj.f();
}
}

Upvotes: 2

Views: 90

Answers (4)

JustinKSU
JustinKSU

Reputation: 4999

Change

b = 1;

to

this.b = 1;

The way you have it now, you are changing the parameter (local) variable not the class member variable.

Upvotes: 6

Mohsin AR
Mohsin AR

Reputation: 3108

  public class Qcb90 {
    int a;
    int b;
    public void f() {
        a = 0;
        b = 0;
        int[] c = { 0 };
        g(b, c);
    // so here b is your instance variable
        System.out.println(a + " " + b + " " + c[0] + " ");
    }
    public void g(int b, int[] c) {
        a = 1;
        //b = 1;  this b is a parameter of your method 
this.b=1; //now run your program


        c[0] = 1;
    }
    public static void main(String[] args) {
        Qcb90 obj = new Qcb90();
        obj.f();
    }
    }

If you want to print b value you need to write this.b inside g()

Upvotes: 0

Matt Jordan
Matt Jordan

Reputation: 2181

The parameter named b in function g(int b, int[] c) hides the class member variable b, so you are setting a local parameter called b to 1 in g(int b, int[] c). This doesn't affect the member variable at all, and the new value is discarded after g exits.

However, the local parameter c is a copy of the pointer to the memory that was allocated in f, so you can modify the contents memory since both copies of the pointer (the copy passed in as a parameter to g and also the original in f) point to the same block of memory.

Upvotes: 0

Bahramdun Adil
Bahramdun Adil

Reputation: 6089

It is because int is not a reference object, for example it is not the object which is created by the word new, so inside the method when you pass b to the method, a new variable will be created for this, and it can just be valid in this method. If an Object that is created by the word new, then it will got affect if it changed by any other method.

Upvotes: 0

Related Questions