Java join array into string
In this post, you will learn how to join an array into a string using the Java programming language.
In the Java programming language, string is object that represents a sequence of characters. Java strings are created and manipulated through the string class. In Java, a string is immutable, which means its value cannot be changed once it is created.
In the development process, we may face some situation where, we need to join the array into a string. Java String class provides a join() method that returns a string joined with a given delimiter. The java.lang.string.join() method is introduced in java string JDK 1.8.
Syntax-String.join(CharSequence delimiter,
Iterable elements)
OR,
String.join(CharSequence delimiter,
CharSequence... elements)
Here, delimiter is the delimiter to be joined with the elements and elements are the elements to be joined. This method returns a string.
Java join array into string
In the given example, we have used the String.join() method to join the elements of the given string array.
public class JoinArray {
public static void main(String args[])
{
String str = String.join(" ", "Worry", "is", "misuse", "of", "imagination");
System.out.println(str);
}
}
Output of the above code:
Worry is misuse of imagination
Java join array into string with Delimiter
To join elements of a given string array with a delimiter, we use the String.join() method and pass the delimiter string followed by the string array.
public class JoinArray {
public static void main(String args[])
{
String str = String.join(" : ", "red", "green", "yellow", "pink", "white");
System.out.println(str);
}
}
Output of the above code:
red : green : yellow : pink : white
public class JoinArray {
public static void main(String args[])
{
String str = String.join(" , ", "Apple", "Orange", "Kiwi", "Pear", "Papaya");
System.out.println(str);
}
}
Output of the above code:
Apple , Orange , Kiwi , Pear , Papaya
Related Articles
Number pattern programs in JavaJava program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number