Menu
Topics Index
...
`


Strings > Special String Operations >
Siva Nookala - 04 Apr 2016
String concatenation is the operation of joining two or more string objects end to end. For example, the concatenation of two strings "Foot" and "ball" is "Football" and the concatenation of three strings "Amar", "Akbar" and "Anthony" is "AmarAkbarAnthony" etc.,

The string class includes concat() method for concatenating two strings. The concat() method is also used for string literals. In general + operator is used for concatenation.
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.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App