Search code examples
javaobjectinstance-variableslocal-variables

Assign instance variables with local variables - Java


When you assign the value of a local string into an instance variable of a class, does it create a new object (String)?

public void setNumber(String number){
    if(number == null || number.length() != 9)
        return;
    this.number = number;
}

Do this implicity works like this:

this.number = new String(number);

Solution

  • The important detail to understand is when you pass a String as a parameter to the setNumber method, you're not passing an object, you're passing a reference so when you do

    this.number = number;
    

    you're taking the reference passed as a parameter and then assigning it to the this.number variable.

    There is no implicit object construction in the aforementioned statement.