Lesson Overview
This lesson introduces arrays, strings, common string methods, number parsing, and arrays of strings.
Arrays
An array stores multiple values of the same data type under one variable name. Each value is accessed by an index. Java array indexes start at 0.
Example declaration:
int[] scores = new int[5];
This creates an integer array with five elements: scores[0] through scores[4].
Alternative syntax:
int scores[] = new int[5];
Both forms work, but int[] scores is commonly preferred because it makes the type clearer.
Assigning and Initializing Array Values
Values can be assigned one at a time.
scores[0] = 90;
scores[1] = 85;
scores[2] = 92;
scores[3] = 88;
scores[4] = 95;
An array can also be initialized immediately.
int[] scores = {90, 85, 92, 88, 95};
Do not place an explicit size when using an initializer list. Java counts the elements automatically.
Activity: Print Array Values
Strings
String is a Java class used to store text. It is available automatically through the java.lang package.
A string can be created using a constructor:
String greeting = new String("Hello");
Most Java code uses the shorter literal form:
String greeting = "Hello";
Strings can be reassigned:
greeting = "Hi";
They can also be combined using concatenation:
String message = greeting + ", learner!";
When at least one side of + is a string, Java usually converts the other value to text and joins them.
Activity: String Assignment and Concatenation
Common String Methods
| Method | Purpose |
|---|---|
equals() | Compares two strings exactly |
equalsIgnoreCase() | Compares strings without considering uppercase/lowercase differences |
toUpperCase() | Converts text to uppercase |
toLowerCase() | Converts text to lowercase |
indexOf() | Finds the first index of a character or substring; returns -1 if not found |
replace() | Replaces matching characters or text |
Activity: String Method Practice
Converting Strings to Numbers
If a string contains numeric characters, it can be converted into a numeric type.
String value = "2470";
int number = Integer.parseInt(value);
number++;
System.out.println(number); // 2471
Use the correct parsing method for the target type:
| Target type | Method |
|---|---|
int | Integer.parseInt(text) |
double | Double.parseDouble(text) |
long | Long.parseLong(text) |
Arrays of Strings
An array can store strings just like it can store numbers.
String[] names = new String[4];
names[0] = "Ana";
names[1] = "Ben";
names[2] = "Cia";
names[3] = "Dan";
It can also be initialized in one line:
String[] names = {"Ana", "Ben", "Cia", "Dan"};
Activity: Print an Array of Strings
Practice Exercises
Laboratory Exercises
Try It: Arrays and Strings
Run this example then try adding more scores to the array or calling other String methods.