In this tutorial, we will discuss toString() method of StringJoiner class. This method is used to get the string representation of StringJoiner object, this includes the delimiter, prefix and suffix.
Example 1: Converting StringJoiner to String
In this example:
- We have created a
StringJoinerobjectedjoinerwith a comma (,) as the delimiter, a left square bracket ([) as the prefix, and a right square bracket (]) as the suffix. - We have added few elements to this
StringJoinerobject. - The
toString()method returns the string representation of this object which is[Chaitanya, Rahul, Aditya]. This string contains the delimiter comma as well as the prefix and suffix brackets.
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("Chaitanya");
joiner.add("Rahul");
joiner.add("Aditya");
String result = joiner.toString();
// Output: [Chaitanya, Rahul, Aditya]
System.out.println(result);
}
}
Example 2: Using toString() on an empty StringJoiner
If there are no elements added to the StringJoiner then in this case, calling the toString() method would return the prefix and suffix of StringJoiner object, if present.
import java.util.StringJoiner;
public class StringJoinerExample {
public static void main(String[] args) {
StringJoiner joiner = new StringJoiner(", ", "[", "]");
String result = joiner.toString();
System.out.println(result); // Output: []
}
}
Leave a Reply