← All posts

How to concatenate two strings in Java

1 min read

SeriesStrings in Javapart 1 of 5
  1. How to concatenate two strings in Java
  2. How to count the occurrences of a character in Java – Three Better Ways
  3. How to use StringTokenizer in Java
  4. How to split a String in Java
  5. How to remove white spaces in Java?

The basic operation we perform daily in Java is concatenating the strings. Concatenation of strings in Java can be achieved in three ways.

  1. Concatenation using + operator.
  2. Concatenation using concat() method of String class.
  3. Concatenation using append() method of StringBuffer class.

Now let us see the each concatenation in detail.

Concatenation using + operator

package com.javaindetail.plusoperator;

public class ConcatUsingPlus {

  public static void main(String[] args) {
    String one = "javaindetail";
    String two = ".com";

    String concatenatedString = one + two;

    System.out.println("Concatenation through variables :: "
        + concatenatedString);

    String concatenatedString2 = "javaindetail" + ".com";

    System.out.println("Direct string concatenation :: " + concatenatedString2);
    System.out.println(concatenatedString + concatenatedString2);

  }

}

** Output:**

Concatenation through variables :: javaindetail.com
Direct string concatenation :: javaindetail.com
javaindetail.comjavaindetail.com

 

Concatenation using concat() method of String class.

package com.javaindetail.plusoperator;

public class ConcatUsingConcatMeothod {

  public static void main(String[] args) {
    String s = "javaindetail";
    s = s.concat(".com");
    System.out.println(s);

  }

}

** Output**

javaindetail.com

 

Concatenation using append() method of StringBuffer class

package com.javaindetail.plusoperator;

public class ConcatUsingApppend {

  public static void main(String[] args) {
    String one = "javaindetail";
    String two = ".com";

    StringBuffer buffer = new StringBuffer();
    buffer.append(one).append(two);

    System.out.println(buffer.toString());

  }

}

** Output**

javaindetail.com