java.lang.String concat()

Description :

This java tutorial shows how to use the concat() method of java.lang.String class. This method returns a new String object which is the result of combining the String object to the method argument String. This method is simply a shortcut in doing the following expression

“this string”+”another string”.

Method Syntax :

public String concat(String str)

Parameter Input :

DataType Parameter Description
String str the string to be combined as a suffix(at the end) to our String object

Method Returns :

This method returns a new String object which is the result of combining our String to that of the String method argument.

Compatibility Version :

Since the beginning

Exception :

N/A

Java Code Example :

This example source code demonstrates the use of concat() method of String class. Basically this source code just prints the concatenated String of our parent String and our input String object.

For this example, we will be showing a practical scenario. First and foremost we will be reading our console for the student first name and last name. The Scanner class will be very useful on this scenario to read the console input from the user. We will be using the concat() method to get the full name by combining the first name and last name. This is an ideal practical scenario to demonstrate the use of this useful string method.

package com.javatutorialhq.java.tutorial.string;

import java.util.Scanner;

/*
 * Example source code for concat method of String class
 * scans user input and combine it to form the full name
 */

public class StringConcatDemo {

    //declare Scanner object
    static Scanner s;
    public static void main(String[] args) {
        // variable declaration
        String firstName;
        String lastName;
        String fullName;
        System.out.print("First Name:");
        s = new Scanner(System.in);
        firstName = s.nextLine();
        System.out.print("Last Name:");
        s = new Scanner(System.in);
        lastName = s.nextLine();
        fullName = firstName.concat(" ").concat(lastName);
        System.out.print("Full name:"+fullName);
        // to avoid memory leak on our scanner object
        s.close();

    }

}

Sample Output :

Running the concat() method example source code of java.lang.String class will give you the following output

concat method example

String concat method example output

Suggested Reading List :