Question

I am confuse about String and String Builder. Here is my simple code

StringBuilder sb1 = new StringBuilder("123");
String s1 = "123";
sb1.append("abc"); 
s1.concat("abc");
System.out.println(sb1 + " " + s1);

sb1 output for 123abc. It is ok! because it use append method.But String s1 should be abc123 but it output is abc. Why? And what is concat method purpose? Please explain me.

Thank you

Was it helpful?

Solution

.But String s1 should be abc123 but it output is abc.

Strings are immutable in Java. concat doesn't change the existing string - it returns a new string. So if you use:

String result = s1.concat("abc");

then that will be "123abc" - but s1 will still be "123". (Or rather, the value of s1 will still be a reference to a string with contents "123".)

The same is true for any other methods on String which you might expect to change the contents, e.g. replace and toLowerCase. When you call a method on string but don't use the result (as is the case here), that's pretty much always a bug.

The fact that strings are immutable is the whole reason for StringBuilder existing in the first place.

OTHER TIPS

concat function not change the string but it returns the result which is not assigned in your case:

String concat(String textToAppend)

so change:

s1 = s1.concat("abc");

string objects are immutable. Immutable simply means unmodifiable or unchangeable

but if you give

String result = s1.concat("abc");

output is 123abc and StringBuilder are mutable you can perform changes

s1.concat("abc") will create a new object in heap with the "abc" concatenated to s1. but s1 is still pointing to original s1 which is "123". so you need to make your s1 reference to point to new object using s1 = s1.concat("abc");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top