Skip to content
Java arrays 6 min read

String Arrays

A String array in Java is simply an array whose elements are String objects instead of primitives. You’ll use them constantly — storing names, reading command-line arguments, holding CSV tokens, and more. Because String is a reference type, there are a few important nuances worth understanding.

Declaring and Initializing a String Array

You can create a String array in several ways:

// 1. Declare then allocate
String[] fruits = new String[3]; // three null slots
fruits[0] = "Apple";
fruits[1] = "Banana";
fruits[2] = "Cherry";

// 2. Declare with an inline initializer
String[] colors = {"Red", "Green", "Blue"};

// 3. new keyword with initializer (less common but valid)
String[] days = new String[]{"Mon", "Tue", "Wed"};

Note: Until you assign a value, each slot holds null — not an empty string. Calling a method on a null element will throw a NullPointerException.

Accessing Elements

Access works exactly like any other array — use a zero-based index:

String[] languages = {"Java", "Python", "Go"};

System.out.println(languages[0]);          // Java
System.out.println(languages.length);      // 3
System.out.println(languages[languages.length - 1]); // Go

Output:

Java
3
Go

Iterating Over a String Array

Traditional for Loop

String[] planets = {"Mercury", "Venus", "Earth", "Mars"};

for (int i = 0; i < planets.length; i++) {
    System.out.println(i + ": " + planets[i]);
}

Output:

0: Mercury
1: Venus
2: Earth
3: Mars

Enhanced for-each Loop

When you don’t need the index, the for-each loop is cleaner:

String[] planets = {"Mercury", "Venus", "Earth", "Mars"};

for (String planet : planets) {
    System.out.println(planet);
}

Comparing Strings in an Array

This is the most common beginner pitfall. Use .equals(), not ==, to compare string values:

String[] names = {"Alice", "Bob", "Charlie"};
String target = "Bob";

for (String name : names) {
    if (name.equals(target)) {           // correct
        System.out.println("Found: " + name);
    }
}

Warning: Using == compares object references, not content. It may accidentally work for string literals (due to the String Pool), but it will silently fail for strings created with new String(...) or read from user input. Always use .equals() or .equalsIgnoreCase().

Sorting a String Array

Arrays.sort() from the Arrays Utility Class sorts a String array alphabetically (lexicographically) in place:

import java.util.Arrays;

String[] animals = {"Zebra", "Ant", "Monkey", "Elephant"};
Arrays.sort(animals);

System.out.println(Arrays.toString(animals));

Output:

[Ant, Elephant, Monkey, Zebra]

Tip: Arrays.sort() on String[] uses a dual-pivot quicksort under the hood. It calls String.compareTo(), which compares Unicode code points — so uppercase letters sort before lowercase ("Apple" before "apple"). Use a case-insensitive sort when needed:

Arrays.sort(animals, String.CASE_INSENSITIVE_ORDER);

Searching a String Array

Linear Search (manual)

String[] tools = {"Hammer", "Wrench", "Screwdriver"};
String search = "Wrench";
int foundAt = -1;

for (int i = 0; i < tools.length; i++) {
    if (tools[i].equals(search)) {
        foundAt = i;
        break;
    }
}

System.out.println(foundAt == -1 ? "Not found" : "Found at index " + foundAt);

Output:

Found at index 1

Binary Search (sorted array only)

import java.util.Arrays;

String[] tools = {"Hammer", "Screwdriver", "Wrench"};
// array must already be sorted
int idx = Arrays.binarySearch(tools, "Screwdriver");
System.out.println("Index: " + idx);

Output:

Index: 1

Warning: Arrays.binarySearch() produces undefined results if the array is not sorted first.

Useful Operations with String Methods

Each element is a full String object, so you can call any String method directly on an element:

String[] words = {"  hello  ", "WORLD", "java"};

for (String w : words) {
    System.out.println(w.trim().toLowerCase());
}

Output:

hello
world
java

Converting Between String Arrays and Other Types

Array to a Single String (String.join)

String[] parts = {"one", "two", "three"};
String joined = String.join(", ", parts);
System.out.println(joined);

Output:

one, two, three

Splitting a String into an Array

String csv = "Alice,Bob,Charlie";
String[] names = csv.split(",");

for (String name : names) {
    System.out.println(name);
}

Output:

Alice
Bob
Charlie

Tip: split() accepts a regular expression. Use split(",\\s*") to also trim any whitespace around each comma.

Array to a List (and back)

import java.util.Arrays;
import java.util.List;

String[] arr = {"A", "B", "C"};
List<String> list = Arrays.asList(arr);   // fixed-size list backed by array

// Back to array:
String[] back = list.toArray(new String[0]);

Note: Arrays.asList() returns a fixed-size list — you can update elements but cannot add or remove them. Use new ArrayList<>(Arrays.asList(arr)) if you need a fully mutable list.

Handling null Elements Safely

String[] data = {"Alice", null, "Charlie"};

for (String item : data) {
    if (item != null) {
        System.out.println(item.toUpperCase());
    } else {
        System.out.println("(empty)");
    }
}

Output:

ALICE
(empty)
CHARLIE

Multi-Dimensional String Arrays

You can have a 2D (or higher) array of Strings — useful for grids, tables, or groupings. See Multidimensional Arrays for the full picture.

String[][] schedule = {
    {"Mon", "Math", "English"},
    {"Tue", "Science", "History"},
    {"Wed", "PE", "Art"}
};

for (String[] day : schedule) {
    System.out.println(day[0] + ": " + day[1] + ", " + day[2]);
}

Output:

Mon: Math, English
Tue: Science, History
Wed: PE, Art

Under the Hood

String arrays are reference arrays. When the JVM allocates new String[5], it creates an array object on the heap containing five reference-sized slots (typically 4 or 8 bytes each, depending on the JVM and pointer compression settings), each initialized to null. The actual String objects live elsewhere on the heap; the array holds only pointers to them.

This has two important implications:

  1. Memory layout — unlike an int[], the string content is scattered across the heap. Iterating a String[] can cause more cache misses than iterating a primitive array, especially for long arrays with large strings.

  2. String interning — string literals in your source code are automatically placed in the String Pool. When you write String[] s = {"Hello", "World"}, both "Hello" and "World" are interned. If another part of your code also uses the literal "Hello", it points to the exact same object in memory.

Sorting a String[] with Arrays.sort() calls String.compareTo() under the hood, which compares char values (UTF-16 code units) one by one — this is an O(n log n) algorithm on the number of strings, and each comparison is O(k) where k is the length of the compared prefix.

For performance-critical code with very large String arrays, consider ArrayList<String> or streaming with the Stream API — but for the vast majority of use cases, a plain String[] is perfectly fast and clear.

Quick Reference

TaskCode
Declare & initializeString[] a = {"x", "y"};
Get lengtha.length
Access elementa[0]
SortArrays.sort(a)
Search (binary)Arrays.binarySearch(a, "x")
Print allArrays.toString(a)
Join to StringString.join(",", a)
Split String"a,b".split(",")
Compare elementsa[0].equals("x")
Convert to ListArrays.asList(a)
  • Arrays — the foundation you need before working with String arrays
  • Strings — deep dive into the String class itself, methods, and immutability
  • String Methods — complete guide to every method you can call on a String element
  • String Comparison — why == is wrong and how .equals(), compareTo(), and equalsIgnoreCase() work
  • Arrays Utility Classsort, binarySearch, copyOf, fill, and more
  • ArrayList — when you need a resizable list of strings instead of a fixed array
Last updated June 13, 2026
Was this helpful?