2 Ways to Concat a String in Java

2 Ways to concat a string in Java
Concatenating a string in Java is the most easiest thing that you'll learn. You might already be familiar with one way using the simple concatenation operator +. Another way to do is to use the concat() method. Not well known, concat() method does the same thing. We don't need to use it, specifically because we can do it using the +.


public String concat(String st)

The calling object and the parameter are joined in the respective order.

class ConcatString
{
        public static void main(String args[])
        {
            // Take 2 strings
            String first=args[0];
            String second=args[1];
          
            // Simple
            String third=first+second;
          
            System.out.println("Concatenated string using + "+third);
            System.out.println("Concatenated string using concat() "+first.concat(second));
        }
}

Update: As you can see, when you are concatenating two strings, you get a new String object, so this is inefficient. I forgot the point and actually, +Arturo Gomez del Castillo recalled it, thank you! Now, the efficient way would be using a StringBuilder class. The append() method does it for you.
If you like this simple post, share it simply. You might also like concatenating unlimited strings.

No comments: