Why does the code print 0 instead of 5?

3

Why does this code print 0 instead of 5 ?

class B {
    private int b;
    public int getB() { return b; }
    public void setB(int b) { b=b; }
}

class A {
    public static void main (String[] args) {
        B b = new B();
        b.setB(5);
        System.out.println(b.getB());
    }
}

Run it via Ideone .

    
asked by anonymous 21.02.2017 / 01:44

3 answers

10

Because the code is assigning the b parameter to the b parameter itself, and the b attribute of the class is not being changed. When there is ambiguity, it overcomes the local symbol. If the parameter had another name, it would work. But since it is not legal to change a name just to get around this, after all this could affect the readability, it should be explicit that you want to change the class variable, indicating with this.b . So:

class B {
    private int b;
    public int getB() { return b; }
    public void setB(int b) { this.b = b; }
}

class A {
    public static void main (String[] args) {
        B b = new B();
        b.setB(5);
        System.out.println(b.getB());
    }
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

    
21.02.2017 / 01:56
3

You must use this.b to reference the attribute of your class. That way, your class B code should be:

class B {
  private int b;
    public int getB() { return this.b; }
    public void setB(int b) { this.b=b; }
}
    
21.02.2017 / 01:58
1

The b=b; code has no effect on the public void setB(int b) method of class B.
When a parameter with the same field name exists, it is necessary to use this to access the field and the reason for printing 0 is because this is the initial value assigned to variables and fields of type int .

    
22.02.2017 / 13:45