[Solved] Modify non immutable object, java


I have one StringBuilder, a non immutable object and if I use a method on the object it will return me a new value of the object with the same reference object.

  • Not always will a method return you the same reference object. It might create a new object and return that. Its always better to check the docs before you assume anything.

Why when I am using a.substring ( int a, int b ), it is not modifying the object StringBuilder?

  • If you read the documentation, it clearly states that substring(int,int) method Returns a new String. That answers why your object is not being modified.

Why if I use the method a.append("value") I am modifying the value of the StringBuilder object?

  • Again if you read the docs for append(String), it clearly states that it – Returns: a reference to this object.. This method complies with what “your thinking” was.

solved Modify non immutable object, java