Java arrays and strings

Work with fixed-size arrays, common String methods, and the difference between == and equals.

Java
class Main {
  public static void main(String[] args) {
    int[] scores = {82, 91, 76};
    int sum = 0;
    for (int score : scores) {
      sum += score;
    }
    System.out.println(scores.length + " scores, total " + sum);

    String text = "Programonic";
    System.out.println(text.length() + " " + text.substring(0, 7) + " " + text.indexOf('m'));

    String[] parts = "a,b,,c".split(",");
    System.out.println(parts.length + " " + String.join("-", parts));

    String first = new String("hi");
    String second = "hi";
    System.out.println((first == second) + " " + first.equals(second));

    System.out.println(new StringBuilder(text).reverse());
  }
}
Output
3 scores, total 249
11 Program 6
4 a-b--c
false true
cinomargorP

Explanation

An array has a fixed length and holds elements of one type, indexed from 0. Reading outside the bounds throws ArrayIndexOutOfBoundsException. A String is an immutable sequence of characters, so its methods return new strings. length, substring, indexOf, split, and String.join cover many everyday tasks.

For objects, == compares references, and equals compares contents. Two strings with the same text can be different objects, so use equals. StringBuilder is a mutable buffer: appending in a loop with it is much cheaper than creating a new String each time. Note that split drops trailing empty strings but keeps empty strings in the middle.

Explore the dry run
Guided walkthroughReady
1class Main {
2 public static void main(String[] args) {
3 int[] scores = {82, 91, 76};
4 int sum = 0;
5 for (int score : scores) {
6 sum += score;
7 }
8 System.out.println(scores.length + " scores, total " + sum);
9
10 String text = "Programonic";
11 System.out.println(text.length() + " " + text.substring(0, 7) + " " + text.indexOf('m'));
12
13 String[] parts = "a,b,,c".split(",");
14 System.out.println(parts.length + " " + String.join("-", parts));
15
16 String first = new String("hi");
17 String second = "hi";
18 System.out.println((first == second) + " " + first.equals(second));
19
20 System.out.println(new StringBuilder(text).reverse());
21 }
22}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
An array of three ints with indexes 0, 1, 2.scores = [82, 91, 76]
—
length is a field of arrays; the loop added 82 + 91 + 76.sum = 249
3 scores, total 249
substring(0, 7) stops before index 7; the first m is at index 6.sum = 249
3 scores, total 249
11 Program 6
The empty string between the commas is kept, so there are four parts.sum = 249
3 scores, total 249
11 Program 6
4 a-b--c
new String creates a distinct object, so == is false, while the contents are equal.sum = 249
3 scores, total 249
11 Program 6
4 a-b--c
false true
StringBuilder can reverse its contents in place.sum = 249
3 scores, total 249
11 Program 6
4 a-b--c
false true
cinomargorP

Cost and common mistakes

Summing is O(n); substring and indexOf are O(length of the text).

  • Use equals, not ==, to compare strings. == may appear to work for literals because of interning, but it is not reliable.
  • Strings are immutable. text.toUpperCase() returns a new string and leaves text unchanged.
  • Building a long string with += in a loop copies it each time, which is O(n²). Use StringBuilder.

Try it yourself

What does "a,b,,".split(",").length return?

Reveal answer and reasoning

2, because split removes trailing empty strings, leaving just a and b.

Further reading