String Concatenation in Java

In this article, we will look at the many ways you can use to concatenate string strings in Java. Without beating around the bush, we shall directly jump into the different ways to concatenate the given strings.

To grasp the concept faster and master it quickly, I suggest you practice each code in the article, try to make some modifications, and tinker with the code to cover different scenarios. This will help you understand the code better and learn how to apply it in different situations.

What is String Concatenation in Java?

The English definition of concatenation is “joining”. In the world of programming too, concatenation means joining. Thus, string concatenation means the joining of strings.

For example, if we concatenate the strings “First” and “Code”, we get a resultant string of “FirstCode”.Let us now take a look at the different ways we can concatenate strings in the Java programming language

Comparing Strings using the ‘+’ operator

You may ask, how can you add 2 strings? They are not numbers to add, are they? Well, you are right, when we use the “+” operator with numbers, it works as an addition operator, but if we use it with strings, it works as a concatenation operator.

This is one fine example of operator overloading. Here is an example of using the “+” operator as a string concatenation operator.

class FirstCode
{  
 public static void main(String args[])
 {  
   String s="First"+" Code";  
   System.out.println("The concatenated string is: "+s); 
 }  
}

Output:

The concatenated string is: FirstCode

In the above code the strings “First” and “Code” have been concatenated to “Firstcode”. Moreover, the Java compiler converts the line “ String s=”First”+” Code”;” into “String s=(new StringBuilder()).append(“Sachin”).append(” Tendulkar).toString();”

Concatenating strings using the concat() method

This inbuilt Java method concatenates the specified string to the end of the current string. For example to concatenate “String1” to “String2”, we use the following syntax: String1 concat(String2)

class FirstCode
{  
 public static void main(String args[])
 {  
   String s1="First ";  
   String s2="Code";  
   String s3=s1.concat(s2);  
   System.out.println("The concatenated string is: "+s3);
  }  
}

Output:

The concatenated string is: FirstCode

In the above code, the strings “First” and “Code” have been concatenated to “Firstcode” by using the concat() method

Concatenating strings using the String Builder class

The StringBuilder class provides an inbuilt method called append() that performs concatenation operations. This method accepts arguments of different types, such as Objects, StringBuilder, int, char, CharSequence, boolean, float, and double.

StringBuilder is one of the most popular and fastest ways to concatenate strings in Java, moreover, since StringBuilder is a mutable class, values stored in StringBuilder objects can be updated or changed. Here is an example of how to use the append() method of the StringBuilder class to concatenate two strings:

public class FirstCode  
{  
    public static void main(String args[])  
    {  
        StringBuilder s1 = new StringBuilder("First");    
        StringBuilder s2 = new StringBuilder(" Code");    
        StringBuilder s = s1.append(s2);  
            System.out.println("The concatenated string is: "+s.toString()); 
    }  
}

Output:

The concatenated string is: FirstCode

Concatenating strings using the format() method

The String.format() method joins multiple strings using format specifiers like %s, which are followed by string values or objects. Here is an example:

public class FirstCode  
{   
    public static void main(String args[])  
    {  
        String s1 = new String("First");   
        String s2 = new String(" Code");   
        String s = String.format("%s%s",s1,s2); 
        System.out.println("The concatenated string is: "+s.toString());  
    }  
}

Output:

The concatenated string is: FirstCode

Concatenating strings using the String.join() method

This inbuilt Java method is available in Java version 8 and higher versions. The String.join() method accepts a separator and an array of String objects as its parameters. Here is an example to understand better:

public class FirstCode  
{  
    public static void main(String args[])  
    {  
        String s1 = new String("First");     
        String s2 = new String(" Code");    
        String s = String.join("",s1,s2);   
        System.out.println("The concatenated string is: "+s.toString());  
    }  
}

Output:

The concatenated string is: FirstCode

Concatenating strings using the String joiner class

The StringJoiner class has all the functionalities of the built-in method String.join(). In advance, its constructor can also accept optional arguments, prefixes, and suffixes. Below is an example to understand its functionality better:

import java.util.*;  
public class FirstCode  
{   
    public static void main(String args[])  
    {  
        StringJoiner s = new StringJoiner(", ");   
        s.add("First");     
        s.add("Code");     
        System.out.println("The concatenated string is: "+s.toString());   
    }  
}

Output:

The concatenated string is: FirstCode

Concatenating strings using the Collectors.joining() method

The Collectors class in Java 8 has a joining() method that joins the input elements in the same order in which they appear. This method takes two arguments: the delimiter to use between the elements and the separator to use for each element.

The delimiter is used to separate the elements, while the separator is used to separate each element from the delimiter. For example, if you have a list of strings and you want to join them together with a comma as the delimiter and space as the separator, you would use the following code:

String joinedString = Collectors.joining(“, “,<list>);

Here is an example code using the Collectors.joining() method to concatenate 2 strings:

import java.util.*;  
import java.util.stream.Collectors;  
public class FirstCode  
{ 
    public static void main(String args[])  
    {  
        List<String> liststr = Arrays.asList("First", "Code", "Rocks");  
        String str = liststr.stream().collect(Collectors.joining(", "));  
        System.out.println(str.toString());   
    }  
}

Output:

First, Code, Rocks

Conclusion

You have now learned multiple how to concatenate strings in Java as we looked at comparing strings using the “+” operator, concat(), String Builder class, format(), String.join(), String Joiner class, and the Collectors.joining().

Leave a Reply

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