Skip to content

am getting a variable value as zero even it assigned with some value in java

I have 3 classes, among the classes, I am trying to play with methods for that from Second class I am passing some values into First class and from there I am passing values to third class

in the Third I am combining 3 parameters and storing in a variable called p.

now I am trying to print p value in Second class using a method which returns p value but it printing as zero but in the setFive() method it printing the actual value.

Please help me with this where i am doing wrong

Tried Code:

class First {
    int x, y, z;

    void setOne(int a, int b, int c) {
        a = a + x;
        b = b + y;
        c = c + z;
        Third obj = new Third();
        obj.setFive(a, b, c);
    }

    void two(int a) {
        this.x = a;
    }

    void three(int a) {
        this.y = a;
    }

    void four(int a) {
        this.z = a;
    }
}

class Second {
    public static void main(String args[]) {
        First f = new First();
        f.two(100);
        f.three(150);
        f.four(170);
        f.setOne(1, 2, 3);
        Third obj = new Third();
        System.out.println(obj.getFive());
    }
}

class Third {
    int p;

    public void setFive(int a, int y, int n) {
        this.p = a + y + n;
    }

    public int getFive() {

        return p;
    }
}

Thanks

Answer

When you do Third obj = new Third(); inside first.setOne(int a,int b,int c), this obj is local to that method, no other object can see it. It is destroyed when the code exits that method

What you need to do it create that Third object in your Second class, and then pass it to First:

Third obj = new Third();
f.setOne(obj, 1, 2, 3);

then on First you need to change the signature to take the object, and call the setter on it:

void setOne(Third obj, int a, int b, int c) {
    a = a + x;
    b = b + y;
    c = c + z;
    obj.setFive(a, b, c);
}