3

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);
4
  • 1
    No. It refers to the same String instance Commented Mar 31, 2018 at 9:14
  • No, and you can easily check. == is used to test for the same instance. If you print the value of this.number == number on the next line you will see it prints true. If you try it with the new String(number) version, it will print false. Commented Mar 31, 2018 at 9:18
  • 1
    Since Java strings are immutable, there is never a reason to do new String(str) implicitly. Commented Mar 31, 2018 at 9:23
  • Java has always been a bad language to learn how objects and references work... You only handle references but you never see one. People should start with C++ and eventually switch to Java. Commented Mar 31, 2018 at 9:28

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.