Arrays hold a fixed-size collection of values of the same type. Strings are technically objects, not primitives, but Java gives them special syntax support.

Arrays

int[] scores = {85, 90, 78, 92};
System.out.println(scores[0]);      // 85 - indexing starts at 0
System.out.println(scores.length);  // 4 - length is a field, not a method

for (int score : scores) {          // enhanced for-loop
    System.out.println(score);
}

An array's size is fixed once created - to grow a collection dynamically, you will want ArrayList, covered in the Collections lesson.

Strings

String name = "Java";
System.out.println(name.length());        // 4
System.out.println(name.toUpperCase());    // JAVA
System.out.println(name.charAt(0));        // J
System.out.println(name.substring(1, 3));  // av
System.out.println(name.equals("Java"));   // true - use .equals(), never ==

Why .equals() and not ==

For objects (including Strings), == checks whether two variables point to the exact same object in memory, not whether their contents are equal. Two separately-created Strings with identical text can fail an == check while .equals() correctly returns true - this is one of the most common early Java bugs.

StringBuilder for building strings in a loop

Strings in Java are immutable - every concatenation creates a new String object. In a loop, this gets expensive. StringBuilder avoids that:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
    sb.append(i).append(", ");
}
System.out.println(sb.toString()); // 0, 1, 2, 3, 4,