Java examples for Language Basics:String
To concatenate Strings onto the end of each other, use the concat() method.
String one = "Hello"; String two = "Java9"; String result = one.concat(" ".concat(two));
Use the concatenation operator to combine the Strings.
String one = "Hello"; String two = "Java9"; String result = one + " " + two;
Use StringBuilder or StringBuffer to combine the Strings.
String one = "Hello"; String two = "Java9"; StringBuffer buffer = new StringBuffer(); buffer.append(one).append(" ").append(two); String result = buffer.toString(); System.out.println(result);
Full source code
public class Main { public static void main(String[] args){ concatExample();/*from w w w . ja va 2 s . com*/ concatOperatorExample(); stringBufferExample(); } public static void concatExample(){ String one = "Hello"; String two = "Java9"; String result = one.concat(" ".concat(two)); System.out.println(result); } public static void concatOperatorExample(){ String one = "Hello"; String two = "Java9"; String result = one + " " + two; System.out.println(result); } public static void stringBufferExample(){ String one = "Hello"; String two = "Java9"; StringBuffer buffer = new StringBuffer(); buffer.append(one).append(" ").append(two); String result = buffer.toString(); System.out.println(result); } }