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
- Java String charAt() example
- Java String concat() example
- Java String contains() example
- Java String endsWith() example
- Java String equals() example
- Java String equalsIgnoreCase() example
- Java String getBytes() example
- Java String indexOf() example
- Java String isEmpty() example
- Java String lastIndexOf() example
- Java String length() example
- Java String replace() example
- Java String split() example
- Java String startsWith() example
- Java String substring() example
- Java String toLowerCase() example
- Java String toUpperCase() example
- Java String trim() example
- Java String valueOf() example
Comments
Post a Comment
Leave Comment