Unlock the Power of Java’s String Join Method
When working with strings in Java, combining multiple elements into a single string can be a daunting task. Fortunately, the join()
method comes to the rescue, making it easy to concatenate elements with a specified delimiter.
The Syntax of Join
The join()
method has two syntax forms:
String.join(delimiter, element1, element2,...)
String.join(delimiter, iterable)
Here, delimiter
is the character or string used to separate the elements, and element1, element2,...
or iterable
are the elements to be joined.
Key Parameters
The join()
method takes two essential parameters:
- delimiter: The character or string used to separate the elements.
- elements: The elements to be joined, which can be a variable number of
CharSequence
objects or aniterable
containingCharSequence
objects.
Noteworthy Points
- Any class implementing
CharSequence
can be passed tojoin()
, includingString
,StringBuffer
, andCharBuffer
. - If an
iterable
is passed, its elements will be joined, provided it implementsCharSequence
.
Return Value
The join()
method returns a new string with the given elements joined using the specified delimiter.
Example 1: Joining CharSequence Objects
Let’s join three strings – “Java”, “is”, and “fun” – using the -
delimiter:
java
String result = String.join("-", "Java", "is", "fun");
System.out.println(result); // Output: Java-is-fun
Example 2: Joining an Iterable
Create an ArrayList
of strings and join its elements using the -
delimiter:
“`java
List
list.add(“Java”);
list.add(“is”);
list.add(“fun”);
String result = String.join(“-“, list);
System.out.println(result); // Output: Java-is-fun
“
join()` method, you can effortlessly combine multiple elements into a single string, making your coding life easier!
With the