Tutorial 1: Arrays, Traversal, and String APIs

Unit 6 ยท Arrays and strings

Objectives

Java arrays have fixed length and zero-based indexes from 0 through length - 1. A traversal should use the array's length rather than a hard-coded endpoint.

int[] marks = {72, 81, 64, 90};
int total = 0;
int highest = marks[0];
for (int mark : marks) {
    total += mark;
    if (mark > highest) highest = mark;
}
System.out.println(total / (double) marks.length);

String objects are immutable. Methods such as trim, toUpperCase, and substring return new strings. Compare content with equals or equalsIgnoreCase.

Practice

  1. Write methods for sum, minimum, and linear search.
  2. Count vowels in a string without changing its case.
  3. Test empty arrays and empty strings where your design permits them.

Self-check

  1. What is the last valid index of an array of length 5?
  2. Why does name.toUpperCase() not change name?
  3. What exception signals an invalid array index?

Mastery task: Create a survey analyzer that stores ratings, reports a distribution, and finds the most common rating.