String Arrays
A railway route is a list of station names. A shopping list is a list of item names. Arrays of text, String[], are some of the most common arrays you'll write. They work like any other array, with three things to know: new slots are null, text is compared with equals, and Java can split a line into an array and join it back.
Creating and Searching
public class Route {
public static void main(String[] args) {
String[] stops = {"Chennai", "Katpadi", "Bengaluru", "Mysuru"};
String wanted = "Bengaluru";
for (int i = 0; i < stops.length; i++) {
if (stops[i].equals(wanted)) {
System.out.println(wanted + " is stop number " + (i + 1));
}
}
}
}Bengaluru is stop number 3Line 6 compares text with equals, not ==. == checks whether two variables point to the same object, which can fail for text built at runtime (the strings lessons, later in the course, explain why). Use equalsIgnoreCase to ignore capital letters.
null vs Empty
public class Blanks {
public static void main(String[] args) {
String[] names = new String[3];
names[0] = "Navika";
names[1] = "";
for (String n : names) {
System.out.println("[" + n + "]");
}
}
}[Navika]
[]
[null]names[1] is an empty string: a real String with no characters. names[2] is null: no String at all. Calling names[2].length() would throw a NullPointerException; names[1].length() is 0.
Sorting, Splitting and Joining
import java.util.Arrays;
public class Words {
public static void main(String[] args) {
String line = "mango banana apple cherry";
String[] fruits = line.split(" ");
Arrays.sort(fruits);
String joined = String.join(", ", fruits);
System.out.println(fruits.length + " fruits: " + joined);
}
}4 fruits: apple, banana, cherry, mangoHow it works
- Line 6:
split(" ")cuts the line at each space and returns aString[]. - Line 7:
Arrays.sortsorts text alphabetically (strictly, by Unicode value, so capital letters come before small ones). - Line 8:
String.joinglues the elements together with", "between them.
Try it yourself: change the line to "Mango banana Apple cherry". Where do the capitalized words end up after sorting?
Common Mistakes
Using == to compare text. It may work in a quick test and fail with input read at runtime. Always use equals.
Calling a method on a null slot. Check if (name != null) or fill every slot first.
Expecting alphabetical order to ignore case. Arrays.sort puts "Zebra" before "apple". Use Arrays.sort(words, String.CASE_INSENSITIVE_ORDER).
Practice
- Easy: Split
"Pune,Nashik,Nagpur"on commas and print each city on its own line. - Harder: Count how many words in a sentence start with a capital letter. Hint:
Character.isUpperCase(word.charAt(0)).
Key Takeaways
Was this tutorial helpful?