String Concatenation in Java

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

In Java, string concatenation is a fundamental task that joins multiple pieces of text into a single string. It’s like putting words together in various situations, like crafting friendly messages or building complex data structures. Java gives us many ways to do this. Each way has its own special features and best uses.

We’ll look at each method with examples to see how they work and when they’re most helpful:

  • Using the + operator
  • Using the concat() method from the String class
  • Using the StringBuilder class
  • Using the format() method
  • Using the join() method (Java 8+)
  • Using the StringJoiner class (Java 8+)
  • Using the Collectors.joining() method (Java 8+)

In this article, we will explore examples of each of these string concatenation methods in Java, allowing you to choose the most suitable technique for your specific programming needs. These methods empower Java developers with a wide array of options for efficiently manipulating strings in their applications.

String Concatenation by + Operator

The simplest way to concatenate two strings is by using the + operator.

Example 1: Basic String Concatenation Using + Operator

public class TestStringConcatenation1 {

  public static void main(String[] args) {

    String firstName = "John";
    String lastName = "Doe";

    String fullName = firstName + " " + lastName;

    System.out.println(fullName);
  }
}

Output:
John Doe

Example 2: Concatenating Strings and Primitive Values Using + Operator

public class TestStringConcatenation2 {

  public static void main(String[] args) {
      
    String name = "John";
    int age = 26;
      
    System.out.println("My name is " + name + " and I am " + age + " years old.");
  }
}

Output:
My name is John and I am 26 years old.

Note that when a + operator is placed after a string literal, the compiler treats the whole expression as a String. So “My name is ” + name is optimized to StringBuilder append operations.

String Concatenation by concat() Method in Java

The String class provides a concat() method that can be used to concatenate two strings:

public String concat(String str);

Example 3: Concatenating Two Strings Using concat()

public class TestStringConcatenation3 {

  public static void main(String[] args) {
      
    String firstName = "John";
    String lastName = "Doe";
      
    String fullName = firstName.concat(" ").concat(lastName);
      
    System.out.println(fullName);
  }
}

This concatenates firstName and lastName with a space using the concat() method.

Output:
John Doe

The concat() method can be used multiple times to concatenate more than two strings.

Other Ways to Concatenate Strings in Java

There are several other classes and methods available in Java for concatenating strings:

String Concatenation Using StringBuilder

The StringBuilder in Java represents a mutable sequence of characters. Since StringBuilder is mutable, it provides an efficient way to concatenate strings.

The key methods are:

  • append() – concatenates the specified string
  • insert() – inserts the specified string at a given index

Example: Concatenating Strings Using append() Method

public class StrBuilder {

  public static void main(String[] args) {

    StringBuilder sb = new StringBuilder();

    sb.append("Hello ");
    sb.append("World");

    System.out.println(sb.toString());  
  }
}

Output:
Hello World

String Concatenation Using format()

The String class provides a static format() method that can be used for formatted string concatenation:

public static String format(String format, Object... args)

Example: Concatenating Strings Using format()

public class StrFormat {

  public static void main(String[] args) {

    String name = "John";
    int age = 26;

    String result = String.format("My name is %s and I am %d years old.", name, age);

    System.out.println(result);
  }
}

Output:
My name is John and I am 26 years old.

String Concatenation Using join()

The String class provides a static join() method since Java 8 that can be used to concatenate string elements from an Iterable:

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

Example: Concatenating Strings Using join()

import java.util.Arrays;

public class StrJoin {

  public static void main(String[] args) {

    String result = String.join("-","Hello","World");

    String result2 = String.join("-", Arrays.asList("Hello", "World"));

    System.out.println(result);
    System.out.println(result2);
  }
}

Output:
Hello-World
Hello-World

This joins “Hello” and “World” using “-” as the delimiter.

String Concatenation Using StringJoiner

The StringJoiner class was also introduced in Java 8 to construct strings using a delimiter:

public final class StringJoiner

The key methods are:

  • add() – adds a new string element
  • merge() – merges another StringJoiner
  • toString() – returns the concatenated string

Example: Concatenating Strings Using StringJoiner

import java.util.StringJoiner;

public class StrJoiner {

  public static void main(String[] args) {
  
    StringJoiner joiner = new StringJoiner("-");

    joiner.add("Hello"); 
    joiner.add("World");

    String result = joiner.toString(); 

    System.out.println(result);
  }
}

Output:
Hello-World

String Concatenation Using Collectors.joining()

The Collectors class provides a joining() method that can concatenate strings from a Stream:

Example: Concatenating Strings Using Collectors.joining()

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ColJoining {

  public static void main(String[] args) {

    Stream<String> stream = Stream.of("Hello", "World");

    String result = stream.collect(Collectors.joining("-"));

    System.out.println(result);
  } 
}

Output:
Hello-World

Conclusion

In summary, Java provides multiple ways to concatenate strings, ranging from the basic + operator to more advanced options such as StringBuilder, StringJoiner, and Collectors.joining().

The concat() method can concatenate two strings, while format() provides formatted string concatenation. For better performance with repeated concatenations, StringBuilder is recommended over basic + concatenation.

The join() method, StringJoiner class, and Collectors.joining() were added in Java 8 to provide delimited string joining capabilities. The choice depends on the specific use case – whether a simple one-off concatenation or repeated concatenations in a loop. But Java provides flexibility for concatenating strings in different scenarios.

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses
Image

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *