exampracticeonline.com
String concat()

Java String concat

The java string concat() method combines two string. It returns combined string. It is like appending another string.

Internally, Java makes another character array with joined length of string item and contention string, and copies all string item from the two strings into this new array. At long last, combiner character array is changed over to string object.

Internal method implementation

You can see this internal implementation in String.class provided in java.lang package.

/**
     * Concatenates the specified string to the end of this string.
     * 
     * Examples:
     * "cares".concat("s") returns "caress"
     * "to".concat("get").concat("her") returns "together"
     *
     * @param   str   the {@code String} that is concatenated to the end
     *                of this {@code String}.
     * @return  a string that represents the concatenation of this object's
     *          characters followed by the string argument's characters.
     */
    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);
    }

Method Syntax

public String concat(String str)

Method Parameter

str: Another String to be combined at the end of first String. 

Method Returns

Java String concat() method returns combined String.

1. Example - Java String concat() method

package com.examples;

public class StringConcatExample {
        
        public static void main(String args[]) {
                String str = "Hello";
                System.out.println("before concat method str: "+str);
                str = str.concat(" Java");
                System.out.println("after concat method str : "+str);
        }
        
}

Output: 

before concat method str: Hello
after concat method str : Hello Java

2. Example - Java String concat() method

Concat one String with another String object.

package com.examples;

public class StringConcatExample {
        
        public static void main(String args[]) {
                String str1 = "Hello";
                String str2 = " Java";
                System.out.println("before concat method str1 : "+str1);
                str1 = str1.concat(str2);
                System.out.println("after concat method str1 : "+str1);
        }
        
}

Output: 

before concat method str1 : Hello
after concat method str1 : Hello Java