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.
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 be concatenated.
Return Value
Returns the new concatenated string.
Example
Example
public
class
Test
{
public
static
void
main
(
String
args
[
]
)
{
String
s
=
"Runoob Tutorial:"
;
s
=
s.
concat
(
"www.runoob.com"
)
;
System
.
out
.
println
(
s
)
;
}
}
The execution result of the above program is:
Runoob Tutorial:www.runoob.com
Notes
- If the argument passed to the
concat()method isnull, aNullPointerException. - If the argument passed to the
concat()method's argument is an empty string (""), the returned string is the same as the string on which theconcat()method was called.
Example
public
class
ConcatExample
{
public
static
void
main
(
String
[
]
args
)
{
String
str1
=
"Hello"
;
// Concatenate an empty string
String
result
=
str1.
concat
(
""
)
;
// Print the result
System
.
out
.
println
(
result
)
;
// Output "Hello"
}
}
In summary, the concat() method is a simple and effective way to concatenate strings, but you should avoid passing null to prevent exceptions.
Java String class