Menu
Topics Index
...
`

Stringconcat method - Java Example Program


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
        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.");
        }
        */    
    }
}
OUTPUT

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

DESCRIPTION

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.

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 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;
    System.out.println(s);
    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;
    System.out.println(s);
    The output of the above code will be 12345, since the numbers 1, 2, 3, 4, 5 are added to the empty string.

© meritcampus 2019

All Rights Reserved.

Open In App