Java String concat() Method Example

1. Introduction

In Java, the String concat() method is used to combine two strings. This method appends the specified string to the end of another string and returns a new concatenated string. This tutorial provides a simple example to demonstrate the usage of the concat() method.

Key Points

- The concat() method is used for string concatenation.

- It returns a new String that represents the concatenation of two strings.

- It is a non-static method, called on an instance of the String class.

2. Program Steps

1. Declare two strings.

2. Use the concat() method to merge them.

3. Print the result.

3. Code Program

public class StringConcatExample {
    public static void main(String[] args) {
        // Declaring the first string
        String firstString = "Hello, ";
        // Declaring the second string
        String secondString = "world!";
        // Concatenating firstString and secondString
        String concatenatedString = firstString.concat(secondString);
        // Printing the concatenated string
        System.out.println(concatenatedString);
    }
}

Output:

Hello, world!

Explanation:

1. String firstString = "Hello, ": Declares and initializes a String variable firstString.

2. String secondString = "world!": Declares and initializes a String variable secondString.

3. String concatenatedString = firstString.concat(secondString): Calls the concat() method on firstString, passing secondString as an argument, and stores the result in concatenatedString.

4. System.out.println(concatenatedString): Prints the concatenated string to the console.


Comments