Insert string in beginning of another string
How to insert a string enclosed with double quotes in the beginning of the StringBuilder and String?
Eg:
StringBuilder _sb = new StringBuilder("Sam");
I need to insert the string "Hello" to the beginning of "Sam" and O/p is "Hello Sam".
String _s = "Jam";
I need to insert the string "Hello" to the beginning of "Jam" and O/p is "Hello Jam".
How to achieve this?
Solution 1:
The first case is done using the insert()
method:
_sb.insert(0, "Hello ");
The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:
String s2 = "Hello " + _s;
Solution 2:
Other answers explain how to insert a string at the beginning of another String
or StringBuilder
(or StringBuffer
).
However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.
When you write:
String s = "Jam";
s = "Hello " + s;
you are actually causing a new String
object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String
object at all.
1 - It is technically possible to use reflection to break abstraction on String
objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String
object was created explicitly via new String(...)
it could be shared, or it could share internal state with other String
objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final
is undefined. Mutation of String
objects is dangerous.
Solution 3:
Sure, use StringBuilder.insert()
:
_sb.insert(0, _s);