Jump to content

String append: Difference between revisions

Line 996:
<syntaxhighlight lang="java">
String string = "abc" + "def";
</syntaxhighlight>
Which can also be written as
<syntaxhighlight lang="java">
String string = "abc";
string += "def";
</syntaxhighlight>
There is also the ''String.concat'' method
Line 1,005 ⟶ 1,010:
StringBuilder string = new StringBuilder();
string.append("abc").append("def");
</syntaxhighlight>
''StringBuilder'' also conveniently lets you insert strings within strings.<br />
So, you can also append a string as follows
<syntaxhighlight lang="java">
StringBuilder string = new StringBuilder();
string.append("abc");
string.insert(3, "def");
</syntaxhighlight>
A less common approach would be to use the ''String.format'' or ''String.formatted'' methods.
Line 1,013 ⟶ 1,025:
String string = "%s%s".formatted("abc", "def");
</syntaxhighlight>
All of these methods will produce the following string
 
<pre>
abcdef
</pre>
<br />
Alternately
118

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.