I am confused with this example :
StringBuilder a = new StringBuilder("abcde");
String subStr = a.substring( a.indexOf("a") , a.indexOf("c") );
int leng = a.length();
char ch = a.charAt(4);
System.out.println( subStr + " " + leng + " " + ch);
//the result will be : subStr = abc , leng = 5 ch = e
My question is : Why ch = e and it doesn't create an Exception ?
My thinking:
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.
- Why when I am using
a.substring ( int a, int b )
, it is not modifying the object StringBuilder ?
- Why if I use the method
a.append("value")
I am modifying the value of the StringBuilder object?
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.
The .substring() method is returning a new String
object, it does not modify the StringBuilder
itself.
Why when i am using a.substring ( int a, int b ) it is not modifying
the object StringBuilder ?
because substring()
returns a new string ,it doesn't modify StringBuilder
.
char ch = a.charAt(4);
, charAt()
returns a char based on the index and since index is zero base ,it returns e
.
Just because an object is 'mutable' does not mean every method that object can perform has to modify it. Common examples are equals(), getClass() ... append() however does modify the StringBuilder object.