⬅ Previous Topic
Java StringcompareToIgnoreCase()
methodNext Topic ⮕
Java Stringcontains()
methodconcat()
method⬅ Previous Topic
Java StringcompareToIgnoreCase()
methodNext Topic ⮕
Java Stringcontains()
methodThe concat()
method in Java is a straightforward way to join two strings together. Think of it like physically attaching two pieces of string – the result is one longer string containing both original sequences.
pubblic String concat(String str)
Parameter | Description |
---|---|
str |
The string to be concatenated with the current string. It can be null , in which case it is treated as an empty string. |
This method returns a new string that is the concatenation of the sequence characters of the current string and the string argument.
Let's start with a simple example. We have two strings, "Hello" and " World", and we want to combine them using concat()
.
String str1 = "Hello";
String str2 = " World";
String result = str1.concat(str2);
System.out.println(result);
Hello World
In this example, str1.concat(str2)
creates a new string that is "Hello" followed by " World". The result is then printed to the console.
What happens if you try to concatenate with an empty string? It doesn’t change the original string, but it still returns a new one.
String str1 = "Java";
String str2 = ""; // An empty string
String result = str1.concat(str2);
System.out.println("Original: "+str1 +", Result:"+result);
Original: Java, Result:Java
Here, concatenating "Java" with an empty string doesn't modify the original string. The result is still "Java". This highlights that concat()
always returns a *new* string.
You can chain multiple calls to concat()
together if you want to combine more than two strings.
String str1 = "Hello";
String str2 = " ";
String str3 = "World";
String result = str1.concat(str2).concat(str3);
System.out.println(result);
Hello World
In this case, we first concatenate str1 with str2 (resulting in " Hello "), and then we concatenate the result with str3 to get "Hello World". This demonstrates how you can build up strings step-by-step.
The concat()
method handles null values gracefully. If you try to concatenate with a null
string, it's treated as an empty string.
String str1 = "Hello";
String str2 = null;
String result = str1.concat(str2);
System.out.println(result);
Hello
Because str2 is null
, it's treated as an empty string when concatenated with “Hello”, so the output remains “Hello”.
⬅ Previous Topic
Java StringcompareToIgnoreCase()
methodNext Topic ⮕
Java Stringcontains()
methodYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.