Menu
Topics Index
...
`

String Concatenation - Java Example Program


String Concatenation
class StringConcatenationTest
{
    public static void main(String arg[])
    {
        String s1 = "Aam";
        String s2 = "Admi";
        String s3 = s1.concat(s2); // LINE A
        System.out.println(s3);
        String s4 = s3 + "Party"; // LINE B
        System.out.println(s4);
        String s5 = "Shaked".concat(" Indian Politics"); // LINE C
        System.out.println(s5);    
    }
}
OUTPUT

AamAdmi
AamAdmiParty
Shaked Indian Politics

DESCRIPTION

At LINE A, adding s1 and s2 string variables using concat method.
At LINE B, "party" is added to "AamAdmi" using + operator.
At LINE C, adding two string literals and displaying the result.

THINGS TO TRY
  • Apply concat method for different string objects and string literals.
  • Apply + operator for more than two string objects.
  • Try for the below code.
    String version = "Java Version".concat(1.7);
    System.out.println(version);
    The above code gives a Compilation Error as concat is not applicable to any other data type other than String.
  • Try for the code.
    String first = "Merit ";
    String second = "Campus";
    Concatenate the above strings using concat method.

© meritcampus 2019

All Rights Reserved.

Open In App