Concatenating Strings - Java Language Basics

Java examples for Language Basics:String

Solution 1

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)); 

Solution 2

Use the concatenation operator to combine the Strings.

String one = "Hello"; 
String two = "Java9"; 
String result = one + " " + two; 

Solution 3

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

Demo 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);
    }
}

Result


Related Tutorials