- 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:
class ConcatTest
{
public static void main(String arg[])
{
String one = "First, solve the problem.";
String two = one.concat(" Then, write the code."); // LINE A
System.out.println(two);
one = "Java";
two = "Tutorial";
String three = one.concat(" ").concat(two); // LINE B
System.out.println(three);
two = one.concat(""); // LINE C
/*
if (one == two)
{
System.out.println("one and two are equal.");
}
else
{
System.out.println("one and two are not equal.");
}
three = one + ""; // LINE D
if (three == one)
{
System.out.println("three and one are equal.");
}
else
{
System.out.println("three and one are not equal.");
}
*/
}
}
OUTPUTFirst, solve the problem. Then, write the code.
Java Tutorial
DESCRIPTIONAt 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
.
THINGS TO TRY
- 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 String
object is created. Now three
holds a new String
object and is different from one
so three and one are not equal. is printed.