§ — — Object-Oriented Programming with Java
This lesson introduces arrays, strings, common string methods, number parsing, and arrays of strings.
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.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
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.
ProReviewer — locked
Drills, code labs, and full solutions.
| 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 |
ProReviewer — locked
Drills, code labs, and full solutions.
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) |
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"};
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
ProReviewer — locked
Drills, code labs, and full solutions.
Run this example then try adding more scores to the array or calling other String methods.
Done with this module? Track it — your progress shows on the subject list.
Up next
Methods→←Previous: Input and Control Statements