CODE
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
}
}
Welcome 2 Merit Campus
Merit Campus
Sun rises in the east.
This statement is true
At 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
.
LINE D
. It produces a NullPointerException
as str1
is null
.LINE E
. str1
contains null
, it is concatenated to number
without any exception. Now str1
contains null2.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=22LINE G
. As parenthesis has the highest priority, arithmetic operation is performed initially and then concatenation is done. This results in Value=4.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.