String concatenation: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 1,122: | Line 1,122: | ||
=={{header|Java}}== |
=={{header|Java}}== |
||
There are multiple ways to concatenate string values in Java.<br /> |
|||
The most common way is through the plus operator. |
|||
<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 |
|||
<syntaxhighlight lang="java"> |
|||
String string = "abc".concat("def"); |
|||
</syntaxhighlight> |
|||
You could use a ''StringBuilder'' object if you're appending multiple strings. |
|||
<syntaxhighlight lang="java"> |
|||
StringBuilder string = new StringBuilder(); |
|||
string.append("abc").append("def"); |
|||
</syntaxhighlight> |
|||
''StringBuilder'' also conveniently lets you insert strings within strings.<br /> |
|||
So, you can also concatenate 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. |
|||
<syntaxhighlight lang="java"> |
|||
String string = String.format("%s%s", "abc", "def"); |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="java"> |
|||
String string = "%s%s".formatted("abc", "def"); |
|||
</syntaxhighlight> |
|||
All of these methods will produce the following string |
|||
<pre> |
|||
abcdef |
|||
</pre> |
|||
<br /> |
|||
Alternately |
|||
<syntaxhighlight lang="java5">public class Str{ |
<syntaxhighlight lang="java5">public class Str{ |
||
public static void main(String[] args){ |
public static void main(String[] args){ |