Learn Java in 10 DaysDay 4: Arrays and Strings

Day 4: Arrays and Strings

What You'll Learn Today

  • Declaring and working with arrays
  • Multidimensional arrays
  • String in depth
  • StringBuilder
  • Array utilities (the Arrays class)

Arrays

An array is a data structure that holds multiple values of the same type.

// Declaration and initialization
int[] numbers = new int[5];          // Array of size 5 (initialized to 0)
int[] scores = {90, 85, 78, 92, 88}; // With initial values

// Access
scores[0]  // 90 (first element)
scores[4]  // 88 (last element)
scores.length  // 5 (number of elements)
flowchart LR
    subgraph Array["scores Array"]
        I0["[0]<br>90"]
        I1["[1]<br>85"]
        I2["[2]<br>78"]
        I3["[3]<br>92"]
        I4["[4]<br>88"]
    end
    style I0 fill:#3b82f6,color:#fff
    style I1 fill:#3b82f6,color:#fff
    style I2 fill:#3b82f6,color:#fff
    style I3 fill:#22c55e,color:#fff
    style I4 fill:#3b82f6,color:#fff

Working with Arrays

int[] numbers = {5, 3, 8, 1, 9};

// Print all elements
for (int num : numbers) {
    System.out.print(num + " ");
}
// 5 3 8 1 9

// Modify an element
numbers[0] = 10;

// Array length
System.out.println(numbers.length); // 5

Note: An array's size cannot be changed after creation. If you need a resizable collection, use ArrayList (covered on Day 9).

Default Values

int[] ints = new int[3];       // [0, 0, 0]
double[] doubles = new double[3]; // [0.0, 0.0, 0.0]
boolean[] bools = new boolean[3]; // [false, false, false]
String[] strs = new String[3];    // [null, null, null]
Type Default Value
int, long 0
double, float 0.0
boolean false
Reference types null

Multidimensional Arrays

// 2D array
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Access
matrix[0][0]  // 1
matrix[1][2]  // 6
matrix[2][1]  // 8

// Print all elements
for (int[] row : matrix) {
    for (int val : row) {
        System.out.printf("%3d", val);
    }
    System.out.println();
}

Jagged Arrays (Irregular Arrays)

int[][] jagged = new int[3][];
jagged[0] = new int[]{1, 2};
jagged[1] = new int[]{3, 4, 5};
jagged[2] = new int[]{6};

The Arrays Class

java.util.Arrays provides utility methods for common array operations.

import java.util.Arrays;

int[] numbers = {5, 3, 8, 1, 9, 2};

// Sort
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
// [1, 2, 3, 5, 8, 9]

// Search (array must be sorted)
int index = Arrays.binarySearch(numbers, 5);
System.out.println(index); // 3

// Copy
int[] copy = Arrays.copyOf(numbers, numbers.length);
int[] partial = Arrays.copyOfRange(numbers, 1, 4);

// Fill
int[] filled = new int[5];
Arrays.fill(filled, 7);
// [7, 7, 7, 7, 7]

// Compare
Arrays.equals(numbers, copy); // true
Method Description
Arrays.sort() Sort the array
Arrays.binarySearch() Binary search (requires sorted array)
Arrays.toString() Convert to string representation
Arrays.copyOf() Copy an array
Arrays.fill() Fill all elements with a value
Arrays.equals() Compare two arrays for equality

String in Depth

Comparing Strings

String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

// == compares references
s1 == s2    // true (string literals are interned)
s1 == s3    // false (new creates a separate object)

// equals() compares values
s1.equals(s2)  // true
s1.equals(s3)  // true

// Case-insensitive comparison
"Hello".equalsIgnoreCase("hello")  // true

Important: Always use equals() to compare strings. == compares references, which can produce unexpected results.

Key Methods

String s = "Hello, Java World!";

// Searching
s.indexOf("Java")      // 7
s.lastIndexOf("l")      // 15
s.contains("Java")      // true

// Transforming
s.toUpperCase()          // "HELLO, JAVA WORLD!"
s.toLowerCase()          // "hello, java world!"
s.trim()                 // Remove leading/trailing whitespace
s.strip()                // Unicode-aware trim (Java 11+)

// Extracting
s.substring(7, 11)       // "Java"
s.charAt(0)              // 'H'

// Replacing
s.replace("Java", "CSS") // "Hello, CSS World!"

// Splitting
String csv = "apple,banana,cherry";
String[] parts = csv.split(",");
// ["apple", "banana", "cherry"]

// Joining
String joined = String.join(" - ", parts);
// "apple - banana - cherry"

Text Blocks (Java 15+)

String json = """
        {
            "name": "Alice",
            "age": 25,
            "city": "New York"
        }
        """;

Recommendation: Use text blocks (""") for multi-line strings.


StringBuilder

Since String is immutable, repeated concatenation is inefficient. Use StringBuilder instead.

// Inefficient (creates a new String object each time)
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i + ", ";
}

// Efficient
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.append(i).append(", ");
}
String result = sb.toString();

Key Methods

StringBuilder sb = new StringBuilder("Hello");

sb.append(" World");       // "Hello World"
sb.insert(5, ",");         // "Hello, World"
sb.delete(5, 6);           // "Hello World"
sb.replace(6, 11, "Java"); // "Hello Java"
sb.reverse();              // "avaJ olleH"
sb.toString();             // Convert to String
flowchart LR
    subgraph Compare["String vs StringBuilder"]
        Str["String<br>Immutable<br>New object on every concat"]
        SB["StringBuilder<br>Mutable<br>Modifies same object"]
    end
    style Str fill:#ef4444,color:#fff
    style SB fill:#22c55e,color:#fff
Class Mutable Thread-Safe Use Case
String No Yes General use
StringBuilder Yes No Bulk concatenation
StringBuffer Yes Yes Multi-threaded concatenation

Practice: String Analyzer

import java.util.Arrays;

public class StringAnalyzer {
    public static void main(String[] args) {
        String text = "Java is a powerful programming language. Java is widely used.";

        // Basic info
        System.out.println("=== String Analysis ===");
        System.out.printf("Characters: %d%n", text.length());
        System.out.printf("Words: %d%n", text.split("\\s+").length);

        // Character frequency
        char target = 'a';
        long count = text.chars().filter(c -> c == target).count();
        System.out.printf("Occurrences of '%c': %d%n", target, count);

        // Sorted word list
        String[] words = text.split("[\\s.]+");
        Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);
        System.out.println("Words (sorted): " + Arrays.toString(words));

        // Reversed string
        String reversed = new StringBuilder(text).reverse().toString();
        System.out.printf("Reversed: %s%n", reversed.substring(0, 20) + "...");
    }
}

Summary

Concept Description
Array Fixed-size collection of same-type elements
Arrays Utility class for array operations
String Immutable string class
equals() Value comparison for strings (don't use ==)
StringBuilder Mutable string (ideal for bulk concatenation)
Text blocks Multi-line strings (Java 15+)

Key Takeaways

  1. Array indices start at 0
  2. Always use equals() for string comparison
  3. Use StringBuilder for repeated string concatenation
  4. Text blocks make multi-line strings clean and readable

Exercises

Exercise 1: Basic

Write a program that finds the maximum, minimum, and average of an integer array.

Exercise 2: Applied

Write a program that takes a string and counts the number of occurrences of each character.

Exercise 3: Challenge

Write a program that checks whether a string is a palindrome (reads the same forwards and backwards). Ignore case and whitespace.


References


Next up: On Day 5, we'll learn about Methods. You'll discover how to organize your code into reusable blocks and keep your programs clean and maintainable.