Java String concat example

Published by admin on

Example of Java String concat() :

concat() method is used to join two strings. It concatenates one string to the end of another string. This method is defined as below :

public String concat(String s)

It takes one string as the parameter. It concatenates this string to the end of the other string and returns the new string. A string is immutable in Java. So, it creates and returns the new string.

 

Example using two strings :

class Example{
    public static void main(String[] args) {
        String str1 = "code";
        String str2 = "color";

        String str = str1.concat(str2);
        System.out.println(str);
    }
}

Output :

codecolor

Java concat example

 

Example using multiple strings :

We can also use the concat method to join multiple strings. concat() method returns one new string. We can call concat() method on this returned string.

class Example{
    public static void main(String[] args) {
        String str1 = "code";
        String str2 = "vs";
        String str3 = "color";

        String str = str1.concat(str2).concat(str3);
        System.out.println(str);
    }
}

Output :

codevscolor

Java multiple concat example

Categories: java

0 Comments

Leave a Reply

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