String Arrays

Naveen AnamaneniUpdated · 3 min read

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

Route.java▶ Try it
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));
            }
        }
    }
}
Output
Bengaluru is stop number 3

Line 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

Blanks.java▶ Try it
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 + "]");
        }
    }
}
Output
[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

Words.java▶ Try it
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);
    }
}
Output
4 fruits: apple, banana, cherry, mango

How it works

  1. Line 6: split(" ") cuts the line at each space and returns a String[].
  2. Line 7: Arrays.sort sorts text alphabetically (strictly, by Unicode value, so capital letters come before small ones).
  3. Line 8: String.join glues 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

  1. Easy: Split "Pune,Nashik,Nagpur" on commas and print each city on its own line.
  2. Harder: Count how many words in a sentence start with a capital letter. Hint: Character.isUpperCase(word.charAt(0)).

Quick check: String arrays

4 questions
1What does a new String[3] contain?
2How should you check whether stops[i] is "Pune"?
3What does "a b c".split(" ") return?
4After Arrays.sort on {"banana", "Apple", "cherry"}, which comes first?

Key Takeaways

Was this tutorial helpful?

Lesson 74 of 482