Java String concat() method example

The Java String concat() method concatenates the method argument string to the end of string object.

1. String concat(String str) method

Internally, Java creates a new character array with combined length of string object and argument string, and copies all content from both strings into this new array. Finally, combiner character array is converted to string object.

public String concat(String str) 
{
    int otherLen = str.length();
    if (otherLen == 0) {
        return this;
    }
    int len = value.length;
    char buf[] = Arrays.copyOf(value, len + otherLen);
    str.getChars(buf, len);
    return new String(buf, true);
}

2. Java String concat example

Java program to concatenate two strings to produce combined string. We can pass an empty string as method argument. In this case, method will return the original string.

public class StringExample 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello".concat(" world"));
    }
}

Program output.

Hello world

3. ‘null’ is not allowed

A 'null' argument is not allowed. It will throw NullPointerException.

public class StringExample 
{
    public static void main(String[] args) 
    {
        System.out.println("Hello".concat( null ));
    }
}

Program output.

Exception in thread "main" java.lang.NullPointerException
	at java.lang.String.concat(String.java:2014)
	at com.StringExample.main(StringExample.java:9)

Happy Learning !!

References:

Java String Doc

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.