C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
New: We can specify the "new String[]" constructor call. This syntax is sometimes clearer.
Java program that uses string arrays, loops
public class Program {
public static void main(String[] args) {
// Create three-element String array.
String[] elements = { "cat", "dog", "mouse" };
// Print element count and first element.
System.out.println(elements.length);
System.out.println(elements[0]);
// Loop over strings in the list with for-each loop.
for (String element : elements) {
System.out.println(element);
}
// Use a longer syntax form for creating the array.
String[] elements2 = new String[] { "bird", "fish", "cow" };
System.out.println(elements2.length);
// Loop over string indexes with for-loop.
for (int i = 0; i < elements2.length; i++) {
System.out.println(elements2[i]);
}
}
}
Output
3
cat
cat
dog
mouse
3
bird
fish
cow
Tip: The argument to toArray on ArrayList can be any String array, even a zero-element one.
Java program that converts ArrayList to string array
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Create an ArrayList of strings.
ArrayList<String> list = new ArrayList<>();
list.add("cat");
list.add("box");
list.add("elephant");
// Use toArray to copy ArrayList to string array.
String[] array = new String[list.size()];
array = list.toArray(array);
// Loop over the string elements in the array.
for (String item : array) {
System.out.println(item);
}
}
}
Output
cat
box
elephant
String.join: This is not called on a string instance. It is static. Be careful to pass the delimiter first, and the array second.
Split: This method returns a String array. It receives only one argument, the delimiter characters (here a comma).
SplitJava program that uses join, split
public class Program {
public static void main(String[] args) {
// This string array contains three values.
String[] values = { "cat", "dog", "spider" };
// Combine these strings together.
String joined = String.join(",", values);
System.out.println(joined);
// Separate the combined string with split.
String[] values2 = joined.split(",");
for (String v : values2) {
System.out.println(v);
}
}
}
Output
cat,dog,spider
cat
dog
spider
Arrays.sort: We import the java.util.Arrays package to easily reference the Arrays.sort method. Sort acts in-place.
Java program that sorts String arrays
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
// Create a string array with four values.
String[] values = new String[4];
values[0] = "zoo";
values[1] = "marina";
values[2] = "amphitheatre";
values[3] = "colloseum";
// Sort the strings.
Arrays.sort(values);
// Display the sorted strings.
for (String v : values) {
System.out.println(v);
}
}
}
Output
amphitheatre
colloseum
marina
zoo