How to use the Java Concat method

The conact method is used to join strings together. Here's a simple example:

String language = "Jav";
String amend = language.concat("a");

System.out.println(amend);

//Prints out Java.

You first type a string name, language in this case. Type a dot after the string name, then add concat. In between the round brackets of concat, enter the text you want to add to the end of the string.

You can chain the concat method. Here's an example that uses concat to construct a name in the format "Personal Name, comma, Family Name":

String personalName = "Kenny";
String familyName = "Carney";
String fullName = "";
fullName = fullName.concat(familyName).concat(", ").concat(personalName);

System.out.println(fullName); //prints Carney, Kenny

The above code uses concat three times. The string we want to build is the fullName string, which starts out empty. We then add the family name, then a comma, then the personalName.

The concat method is useful in loops when you want to build up a string. It saves you from doing this:

String temp = temp + extra;

Instead, you can just use concat:

String temp = temp.concat(extra);

Here's an example that doesn't do much except gets you a lot of letter A's:

String padWithA = "A";
String concatResult = "";

for (int loopVal = 0; loopVal < 5; loopVal++) {

concatResult = concatResult.concat(padWithA);

}

System.out.println(concatResult);

//Prints: AAAAA

There's a more useful example of using concat in loops here, in the Random number section.

In the next lesson, you'll learn how to use the indexOf method

<-- Comparing Strings | indexOf -->

Back to the Java Contents Page

All Home and Learn Courses