Module 5

Module 5: Arrays and Strings

Module 5: Arrays and Strings


5.1 Introduction

In this module, we’ll learn two of the most essential structures in Java — arrays and strings. Arrays store multiple values of the same type, while strings are sequences of characters. Mastering both is crucial for data handling and logic building.

5.2 What Is an Array?

An array is a fixed-size collection of elements of the same data type stored in contiguous memory locations.

Example:

int[] numbers = new int[5];      // Array of 5 integers
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

System.out.println(numbers[2]);  // Output: 30

You can also initialize arrays directly:

int[] scores = {90, 85, 88, 92, 95};

Array Characteristics

  • All elements have the same type.
  • Array size is fixed once created.
  • Access elements using index (starting from 0).

5.3 Iterating Through Arrays

You can access array elements using for or for-each loops.

Using a for loop:

int[] nums = {1, 2, 3, 4, 5};
for (int i = 0; i < nums.length; i++) {
    System.out.println("Element " + i + ": " + nums[i]);
}

Using a for-each loop:

for (int n : nums) {
    System.out.println(n);
}

5.4 Multi-Dimensional Arrays

Java also supports arrays with more than one dimension, such as matrices.

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

System.out.println(matrix[1][2]); // Output: 6

5.5 The java.util.Arrays Class

The Arrays utility class provides useful methods for handling arrays.

import java.util.Arrays;

int[] arr = {3, 1, 4, 1, 5, 9};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // [1, 1, 3, 4, 5, 9]

5.6 Strings in Java

Strings are objects in Java that represent sequences of characters, enclosed in double quotes (" ").

String greeting = "Hello, World!";
System.out.println(greeting.length());        // 13
System.out.println(greeting.toUpperCase());   // HELLO, WORLD!
System.out.println(greeting.charAt(7));       // W

String Concatenation

String firstName = "Liam";
String lastName = "Tang";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // Liam Tang

String Comparison

Never compare strings with == (it checks memory reference). Use equals() instead.

String a = "Java";
String b = new String("Java");

System.out.println(a == b);        // false
System.out.println(a.equals(b));   // true

5.7 Useful String Methods

  • length() – returns length of string
  • charAt(int index) – returns character at position
  • substring(start, end) – extracts substring
  • contains() – checks if substring exists
  • replace(old, new) – replaces text
  • split() – splits string into array
  • trim() – removes leading/trailing spaces

Example:

String sentence = " Java is fun ";
String[] words = sentence.trim().split(" ");
System.out.println("Words: " + Arrays.toString(words));

5.8 StringBuilder

Strings are immutable — every modification creates a new object. Use StringBuilder for efficient string operations.

StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");
sb.insert(5, ",");
System.out.println(sb.toString()); // Hello, Java

5.9 Practice Exercises

  1. Average Calculator: Input 5 numbers in an array and print their average.
  2. Array Search: Check if a number exists in an array and display its index.
  3. String Reversal: Reverse a string entered by the user.
  4. Count Words: Ask the user for a sentence and count how many words it has.
  5. Matrix Sum: Create two 3×3 matrices and add them element-wise.

5.10 Summary

  • Arrays store fixed-size data collections of the same type.
  • Use loops to iterate through arrays.
  • The Arrays class simplifies sorting, comparing, and printing arrays.
  • Strings are objects; use equals() for comparison.
  • Use StringBuilder for efficient string manipulation.

Latest Notes

View Archive [ -> ]