Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
code 1:
    StringBuilder sb1 = new StringBuilder("123456");
    sb1.substring(2, 4);
    sb1.deleteCharAt(3);
    sb1.reverse();
    System.out.println(sb1);

output :
65321

Java
code 2:
String s = "java2s".replace('a', 'Z').trim().concat("Aa");//line 1
    s.substring(0, 2);//line 2
    s.concat("Bb");//line 3
    System.out.println(s);

output :
jZvZ2sAa

What I have tried:

code 1 :In java String is immutable whereas StringBuilder and StringBuffer are mutable but, why substring() method doesn't make any changes in sb1 even though its a StringBuilder object?

code 2:In line 1 concat() method made a change in the String "java2s" but why it doesn't happen so in line 3?

Could anyone please clear my doubts?
Thanks in advance.
Posted
Updated 20-Jul-18 21:24pm
v3

1. The substring method returns the specified characters, it does not affect the existing string. See substring (Java Platform SE 7 )[^].

2. The concat method creates a new string by concatenating the original with the new characters, and returns the newly created string. The original remains unchanged; that is what immutable means.
 
Share this answer
 
v2
Because substring returns a new string, it does not affect the original in any way, be it a string or a stringbuilder.

Concat does the same thing: it returns a new string which is a combination of the parameters - it doesn't affect inputs in any way.

Think about it as numbers:
24 + 77
Returns the value 101 - it doesn't change the number 24 or 77 to 101 and you would not expect it to. So why would you expect concatenation of your first name with your second name to change either? If I concatenate mine: "Paul" and "Griffin" correctly, I get a different object, my "formal name": "Paul Griffin". That doesn't change what my mother used to call me: "Paul", or what policemen call me: "Mr Griffin".
 
Share this answer
 
Comments
Richard MacCutchan 21-Jul-18 5:20am    
So you are well known to the police ...
OriginalGriff 21-Jul-18 5:46am    
Small town ... large motorcycles ... :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900