Java String concat() example

In this guide, you will learn about the String concat() method in Java programming and how to use it with an example.

1. String concat() Method Overview

Definition:

The concat() method in Java's String class is used to concatenate the specified string to the end of another string.

Syntax:

str1.concat(str2)

Parameters:

- str2: The string that is concatenated to the end of str1.

Key Points:

- If the length of the argument string str2 is 0, then the original string (str1) is returned.

- The concat() method does not change the original string. Instead, it returns a new string resulting from the concatenation.

- It's an alternative to using the + operator for string concatenation.

- If str2 is null, then a NullPointerException is thrown.

2. String concat() Method Example

public class ConcatExample {
    public static void main(String[] args) {
        String greeting = "Hello";
        String name = "World";

        // Using concat() to join two strings
        String result = greeting.concat(", ").concat(name).concat("!");
        System.out.println(result);

        // Attempting to concatenate a null string
        try {
            String nullString = null;
            greeting.concat(nullString);
        } catch (NullPointerException e) {
            System.out.println("Error: Cannot concatenate a null string.");
        }
    }
}

Output:

Hello, World!
Error: Cannot concatenate a null string.

Explanation:

In the provided example, we first concatenate the string "Hello" with ", ", then with "World", and finally with "!". This results in the output "Hello, World!". 

Following that, we intentionally try to concatenate a null string to demonstrate the NullPointerException. The catch block captures this exception and prints an appropriate error message.

Related Java String Class method examples

Comments