Topics Index

String Concatenation Demo - Java Example Program

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
        str2 = str2.concat(str3); // LINE B
        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 integeris concatenated to a Stringand a Stringis 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 booleanis concatenated to the String.

  • 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.

© meritcampus 2019

All Rights Reserved.

Open In App