Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
string
concat
communitycreator

How to concatenate strings in Java

Tarun Telang

Concatenation is the process of combining two or more strings to form a new string by subsequently appending the next string to the end of the previous strings.

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java.lang.String class.

This shot will discuss how to perform string concatenation using both of these methods.

String concatenation

Code

Example 1

The program below demonstrates how to concatenate two strings using the + operator in Java.

class HelloWorld {
    public static void main( String args[] ) {
        String first = "Hello"; 
        String second = "World";

        String third = first + second;
        System.out.println(third);

        // yet another way to concatenate strings
        first += second;
        System.out.println(first);        
    }
}
Concatenating two strings using + operator

The concat() method

The signature of the concat() method is shown below:

Syntax


String concat(String stringToConcat)

Parameter

stringToConcat is the string to be concatenated. It will be appended at the end of the string object calling this method.

Return type

The concat() method returns the concatenated string.

Example 2

The program below demonstrates the concatenation using the String.concat() method with two strings in Java:

class HelloWorld {
    public static void main( String args[] ) {
        String first = "Hello"; 
        String second = "World";

        String third = first.concat(second); 
        System.out.println(third);
    }
}
Concatenating two strings using concat() method

Note: You can also directly concatenate the strings within the println method itself as System.out.println(first + second); or System.out.println(first.concat(second));.

RELATED TAGS

java
string
concat
communitycreator
RELATED COURSES

View all Courses

Keep Exploring