Java result after using a method isn’t as expected

i have the following snipet of code :

class Phone {
    String phoneNumber = "123456789";
    void setNumber () {
        String phoneNumber;
        phoneNumber = "987654321";
    }
}
class TestPhone {
    public static void main(String[] args) {
        Phone p1 = new Phone();
        p1.setNumber();
        System.out.println (p1.phoneNumber);
    }
}

im expecting “987654321” as result, but im getting “123456789” it is like the method setNumber is without any effect can anyone helps me to understand please

Answer

Your re-declaring the phoneNumber variable inside the method, shadowing the field in the class, and so any changes made to the local variable will not be seen in the shadowed class field. Don’t do this; get rid of the repeat variable declaration, so that changes made within the method will be seen in the field.

e.g., change this:

void setNumber () {
    String phoneNumber; // *** this is a local variable, visible ONLY in the method!
    phoneNumber = "987654321";  // this has no effect on the field
}

to this:

void setNumber () {
    // String phoneNumber;
    phoneNumber = "987654321"; // this will change the field!
}

Leave a Reply

Your email address will not be published. Required fields are marked *