Milan Vucic
Programming Tutor at Codementor.io

String Concatenation in Java

Published in the Java Developer group
Java String concatenation is an operation to join two or more strings and return a new one. Also, the concatenation operation can be used to cast types to strings. You can concatenate strings in Java in two different ways.

concat() method

Concat() method appends the specified string at the end of the given string and then returns and then returns a new string formed. Sure we can use the concat() method to join three or more strings.

The concat() method signature


public String concat(String str)
The method concatenates the string str at the end of the current string. For example:

String s1 = “Hello ”; 
s1.concat("World")
returns a new string “Hello World”.

Concat() method example

Let’s concat two strings after their initialisation, then concat more strings. And one more interesting example: we are going to create a method that would return different messages according to argument.

public class ConcatTest {

    public static void main(String[] args) {
        //String concat with concat() method 
        String string1 = "I learn ";
        String string2 = "concatenation in Java";
        //here we use concat() method to join the two strings above
        String result = string1.concat(string2);
        System.out.println(result);
        //concat() method to join 4 strings
        String myWebSite = "Code".concat("Gym").concat(".cc").concat("/quest");
        System.out.println(myWebSite); // here we've got  "CodeGym.cc/quest"

        System.out.println(myMessage(true));
        System.out.println(myMessage(false));
    }

    private static String myMessage(boolean b) {   //concat() method with selection statement 
        return "I have".concat(b ? " " : "n't ").concat("got it");
    }

}
The output is:
I learn concatenation in Java CodeGym.cc/quest I have got it I haven't got it
It’s important to know that the concat() method doesn’t change the string, but creates a new one as a result of merging the current one and the one passed as a parameter. So the method returns a new String object, that’s why you can create such long chains of String concat.

Concatenation using overloaded operators "+" and "+="

You can use these two operators in the same way as with numbers. They work just like concat(). Let’s concatenate the string “Code” and string “Gym”.

public class StringConcat {
   public static void main(String[] args) {

       String myString = "Code" + "Gym";
       myString+= ".cc";
       System.out.println(myString);
   }
}
Usually Java doesn’t allow overloading operations for user classes, but these two operators work as overloaded. You might think that inside the + operator is hiding concat(), but in fact, another mechanism is used here. If we look at the Java program bytecode, we’ll see that StringBuilder was created and its append() method is used. The Java Compiler sees the “+” operator and realizes that operands are strings, not primitive types. So it works like concat.

public class StringTest2 {

   public static void main(String[] args) {

       String hello = "hello";
       String world = " world!";

       String helloworld = (new StringBuilder().append(hello).append(world).toString());
       System.out.println(helloworld);
       //this is the same as:
       String result = hello + world;
   }
}

Concat(0) or + ?

If you need to merge strings only once, use the concat() method. For all other cases, it is better to use either the + or Stringbuffer/StringBuilder operator. Also, the + operator is used to convert types. If one of the operands is equal, for example, the number and the second is a string, then at the exit we will get a string. Example:

public class StringConcat {
   public static void main(String[] args) {
       int myInt = 5;
       String myString = " days";

       System.out.println(myInt + myString);
       boolean b = (myInt + myString) instanceof String;
       System.out.println(b);
   }
}
We used instanceof to check if (myInt + myString) a String. Here is the output of this program:
5 days true
Also note that the + operator and concat() work differently if one of the strings is null. If one of the operands when using the + or += operator is only one — a string, then, as we have already said, type conversion occurs. The same applies to null. We'll just get a new string:

public class StringConcat {
   public static void main(String[] args) {

       String myString = "book ";
       System.out.println(myString + null);
       System.out.println((myString + null) instanceof String);
   }
}
The output is:
book null true
String Concatenation in Java - 1If we apply the concat() method for the same operation, then we will get a NullPointerException.

public class StringConcat {
   public static void main(String[] args) {

       String myString = "book ";
       System.out.println(myString.concat(null));

   }
}
The output is:
Exception in thread "main" java.lang.NullPointerException at java.base/java.lang.String.concat(String.java:1972) at StringConcat.main(StringConcat.java:6)
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION