A string can be concatenated with various data types. They include int
, float
, double
, boolean
, references etc.,
String concatenation can be done in two ways
- Using the concatenation operator '
+
'.
As
Strings
are immutable objects a
new String
object is created for every concatenation operation.
The
concat()
method accepts only strings as arguments
i.e. using
concat()
only strings can be concatenated while the '
+
' operator converts the given argument to a string (using
toString()
method for objects).
How the '
+
' operator works:
String str1 = "Merit", str2 = "Campus";
String str = str1 + str2;
- If any of the operands of '
+
' operator is a String
it works as a concatenation operator otherwise as an arithmetic operator.
- Initially a new
StringBuilder
object is created for one of the operand, assume str1
, the other operand is appended to this StringBuilder
object and finally converted to String
object using toString()
method and is assigned.
String Concatenation Demo
class StringConcatDemo
{
public static void main(String arg[])
{
String str1 = "Welcome ", str2 = " Merit", str3 = " Campus";
int number = 2;
str1 = str1 + number + str2 + str3; // LINE A
System.out.println(str1);
str2 = str2.concat(str3); // LINE B
System.out.println(str2);
boolean east = true;
System.out.println("Sun rises in the east." + "\nThis statement is " + east); // LINE C
str1 = null;
// str1 = str1.concat(str2 + str3); // LINE D
// str1 += number; // LINE E
// System.out.println(str1);
// System.out.println("Value=" + number + number); // LINE F
// System.out.println("Value=" + ( number + number) ); // LINE G
}
}
OUTPUTWelcome 2 Merit Campus
Merit Campus
Sun rises in the east.
This statement is true
DESCRIPTIONAt LINE A,
an integer
is concatenated to a String
and a String
is concatenated to another String
, the result of the operation is Welcome 2 Merit Campus.
At LINE B,
concatenation is done using concat()
method. Now the str2
contains Merit Campus.
At LINE C,
a boolean
is concatenated to the String
.
THINGS TO TRY
- Uncomment
LINE D
. It produces a NullPointerException
as str1
is null
.
- Uncomment
LINE E
. str1
contains null
, it is concatenated to number
without any exception. Now str1
contains null2.
- Uncomment
LINE F
. Here the expression is evaluated from left to right. The expression is parsed as ( ("Value=" + number) + number)
. Two operations are concatenation operations, producing the result Value=22
- Uncomment
LINE G
. As parenthesis has the highest priority, arithmetic operation is performed initially and then concatenation is done. This results in Value=4.
- Try to concatenate an object reference or any other data type to a
String
object. For example define a new class A and create an object using new
and add that object reference to the string. Don't forget to print after adding the reference.