Java Reference
In-Depth Information
Use the concatenation operator to combine the strings in a shorthand manner. In the
following example, a space character has been placed in between the two strings:
String one = "Hello";
String two = "Java8";
String result = one + " " + two;
The result is this:
Hello Java8
Solution #3
Use StringBuilder or StringBuffer to combine the strings. The following ex-
ample demonstrates the use of StringBuffer to concatenate two strings:
String one = "Hello";
String two = "Java8";
StringBuffer buffer = new StringBuffer();
buffer.append(one).append(" ").append(two);
String result = buffer.toString();
System.out.println(result);
The result is this:
Hello Java8
How It Works
The Java language provides a couple of different options for concatenating strings of
text. Although none is better than the others, you may find one or the other to work bet-
ter in different situations. The concat() method is a built-in string helper method. It
has the ability to append one string onto the end of another, as demonstrated by solu-
tion #1 to this recipe. The concat() method will accept any string value; therefore,
you can explicitly type a string value to pass as an argument if you want. As demon-
strated in solution #1, simply passing one string as an argument to this method will ap-
pend it to the end of the string, which the method is called upon. However, if you
Search WWH ::




Custom Search