Topics Index

Strings > Modifying a String >
Siva Nookala - 15 Apr 2016
The concat() method appends the specified string to the end of this string. Syntax :
public String concat(String s)

  • This method returns a String object. As strings are immutable objects, a new String object is created on concatenation.
  • If the argument string is an empty string then this String object is returned. Otherwise, a new String object is created, which contains the string after concatenation.
Here is a sample program which illustrates this method:
Stringconcat method
class ConcatTest
    public static void main(String arg[])
        String one = "First, solve the problem.";
        String two = one.concat(" Then, write the code."); // LINE A
        one = "Java";
        two = "Tutorial";
        String three = one.concat(" ").concat(two); // LINE B
        two = one.concat(""); // LINE C
        if (one == two)
            System.out.println("one and two are equal.");
            System.out.println("one and two are not equal.");
        three = one + ""; // LINE D
        if (three == one)
            System.out.println("three and one are equal.");
            System.out.println("three and one are not equal.");

First, solve the problem. Then, write the code.
Java Tutorial


At LINE A, one is concatenated with two at the end.
At LINE B, initially one is concatenated with string " " and then it is concatenated with two.

  • Uncomment the statements. At LINE C, one is concatenated with an empty string. The concat method returns one object, no new object is created here. As both one, two are same so one and two are equal. is printed.
  • At LINE D, empty string is concatenated with one using '+' operator. The '+' operator concatenates empty string with one, a new Stringobject is created. Now three holds a new String object and is different from one so three and one are not equal. is printed.
  • Try for the below code.
    String s = "One" + 1;
    The output of the above code is One1 since the integer value is added to string One.
  • Try for the below code.
    String s = "" + 1 + 2 + 3 + 4 + 5;
    The output of the above code will be 12345, since the numbers 1, 2, 3, 4, 5 are added to the empty string.

Dependent Topics : Java String  

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App