Java concat() Method
In Java, the concat() method is used to concatenate two strings.
This method belongs to the String class and can be used to append one string to the end of another string.
Note that the concat() method does not modify the original string, but returns a new string.
Syntax
public String concat(String s)
Parameters
s-- The string to concatenate.
Return Value
Returns the new concatenated string.
Example
Example
public class Test {
public static void main(String args[]) {
String s = Example:;
s = s.concat("www.example.com");
System.out.println(s);
}
}
public static void main(String args[]) {
String s = Example:;
s = s.concat("www.example.com");
System.out.println(s);
}
}
The above program produces the following result:
Example:www.example.com
Notes
- If passed to
concat()the method's parameter isnull, then it will throwNullPointerException。 - If passed to
concat()the method's parameter is an empty string (""), the returned string is the same as the string callingconcat()the method.
Example
public class ConcatExample {
public static void main(String[] args) {
String str1 = "Hello";
// Concatenating an empty string
String result = str1.concat("");
// Print the result
System.out.println(result); // Outputs "Hello"
}
}
public static void main(String[] args) {
String str1 = "Hello";
// Concatenating an empty string
String result = str1.concat("");
// Print the result
System.out.println(result); // Outputs "Hello"
}
}
In summary, the concat() method is a simple and effective way to concatenate strings, but care must be taken to avoid passing null to prevent exceptions.
Other Extensions
Java String Class