2

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();
}
}
John specter
  • 161
  • 14

4 Answers4

6

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.

JustinKSU
  • 4,875
  • 2
  • 29
  • 51
0

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.

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
0

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.

Matt Jordan
  • 2,133
  • 9
  • 10
0
  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()

Mohsin AR
  • 2,998
  • 2
  • 24
  • 36
  • i would like to vote you up, but im not permitted to do so, im a novice here. i need to earn more reputation score to do so. sorry dude – John specter Mar 01 '16 at 17:59