Difficulty: Beginner to Intermediate | Prerequisites: Java Identifiers, Variables, Data Types and Operators
Strings in Java are objects with built-in methods for searching, comparing, and slicing text. Arrays are fixed-size containers that hold elements of a single type, accessed by zero-based index. 2D arrays extend this to rows and columns, and both kinds are iterated with for loops or enhanced for-each loops.
String concatenation (+)
Joining two strings together with the + operator to produce a new string. "12" + "34" gives "1234".
Think of it as gluing two pieces of text end to end.
charAt(int index)
Returns the single character at the given index position in a string. Indices start at 0.
equals(String other)
Compares two strings for identical content. Returns true if every character matches, false otherwise.
In simple terms, this is the correct way to check whether two strings contain the same text. Do not use == for this.
compareTo(String other)
Compares two strings in alphabetical (lexicographic) order. Returns a negative number if the calling string comes first, a positive number if it comes after, and 0 if they are identical.
indexOf(String or char)
Returns the index of the first occurrence of the given character or substring. Returns -1 if not found.
length()
Returns the number of characters in the string, including spaces.
substring(int startIndex, int endIndex)
Returns a portion of the string starting at startIndex and going up to, but not including, endIndex.
Think of it as cutting out a slice. The start position is included; the end position is not.
Array
A fixed-size, ordered collection of elements, all of the same type, stored in contiguous memory. Accessed by a zero-based integer index.
Think of it as a row of numbered boxes, all holding the same kind of thing.
Index
The position number of an element in an array or string. Java uses zero-based indexing, so the first element is at index 0.
2D array
An array of arrays, organised into rows and columns. Accessed with two indices: array[row][column].
Think of it as a grid or table of values.
Enhanced for loop (for-each)
A loop that iterates through every element in an array without using an index variable. Syntax: for (type element : array).
ArrayIndexOutOfBoundsException
A runtime error thrown when code attempts to access an array index that does not exist (negative, or equal to or greater than the array's length).
Using String s1 = "GREEN"; as an example (indices: G=0, R=1, E=2, E=3, N=4):
s1.charAt(2) returns 'E'
s1.equals(s1) returns true
s1.compareTo(s1) returns 0 (identical strings)
s1.indexOf('E') returns 2 (the first occurrence of E)
s1.length() returns 5 (spaces would also count)
s1.substring(0, 4) returns "GREE" (includes index 0, excludes index 4)
String concatenation with + joins characters from both strings:
"1234" + "1" produces "12341"
Two valid forms:
type[] arrayName = new type[size];
type[] arrayName = {value1, value2, value3};
Common errors:
int[4] = new int[]; (no name, and the size belongs on the right side)
int[] nums = new int[3,2,4,1]; (use {3,2,4,1} with curly braces if you want to set values directly)
int[] nums = {3.14, 5.0, 's'}; (values do not match the declared int type)
Given an array nums containing {23, 48, 97, 0, 1}:
nums[0] returns 23 (first element)
nums[2] returns 97
nums[2] = 35; changes the value at index 2 to 35, so the array becomes {23, 48, 35, 0, 1}
Enhanced for loop (for-each):
int[] nums = {1, 2, 3};
for (int n : nums) {
System.out.println(n);
}Standard for loop:
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}Both produce the same output. The enhanced for loop is simpler but does not give you access to the index. The standard for loop is needed when you need to know or use the index.
Syntax: type[][] name = new type[rows][columns];
Example: int[][] nums = new int[2][3]; creates a grid with 2 rows and 3 columns.
Sample 2D array:
Col 0 | Col 1 | Col 2 | |
|---|---|---|---|
Row 0 | 43 | 2 | 0 |
Row 1 | 6 | 87 | 4 |
nums[0][0] returns 43
nums[1][2] returns 4
nums[2][0] throws ArrayIndexOutOfBoundsException (there is no row 2)
nums[0][0] = 46; changes that cell to 46
Enhanced for loop:
int[][] nums = {{1,2,3},{1,2,3},{1,2,3}};
for (int[] row : nums) {
for (int col : row) {
System.out.println(col);
}
}Standard nested for loop:
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
System.out.println(nums[i][j]);
}
}nums.length gives the number of rows. nums[0].length gives the number of columns.
Students often compare strings with == instead of .equals(). The == operator checks whether two variables point to the same object in memory, not whether the text content is identical.
Students forget that substring(start, end) excludes the end index. "GREEN".substring(0, 4) returns "GREE", not "GREEN".
Students assume arrays are indexed from 1. Java arrays start at index 0. An array of size 5 has valid indices 0 through 4.
Students mix up row and column order in 2D arrays. The first bracket is always the row, the second is the column: nums[row][col].
⚠️ String method questions are common. Be ready to trace through charAt, indexOf, substring, and length on a given string.
⚠️ Know the difference between .equals() and == for strings. This appears on nearly every introductory Java exam.
⚠️ Array declaration syntax is frequently tested. Know which declarations compile and which do not.
⚠️ 2D array questions will ask you to identify the value at a specific [row][col], or to predict what a nested loop prints.
What does "HELLO".charAt(1) return?
Answer: 'E'
True or false: "HELLO".substring(1, 3) returns "ELL".
Answer: False. It returns "EL" (indices 1 and 2, excluding 3).
Fill in the blank: To get the number of elements in an array arr, use arr.____.
Answer: length
True or false: int[] nums = {1.5, 2.5}; compiles.
Answer: False. The values are not integers.
In a 2D array, which index comes first: row or column?
Answer: Row.
Q: Given String s = "JAVA";, what does s.indexOf('A') return?
A: 1. The first occurrence of 'A' is at index 1.
Q: What does s.substring(1, 3) return when s = "JAVA"?
A: "AV". Indices 1 and 2 are included; index 3 is excluded.
Q: Given int[][] grid = new int[3][4];, what is the valid range of row indices?
A: 0 to 2. There are 3 rows, so valid indices are 0, 1, and 2.
Q: Write two different ways to iterate through all elements of int[] nums = {10, 20, 30}; and print each value.
A: Enhanced for loop: for (int n : nums) { System.out.println(n); } Standard for loop: for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); }
Q: What happens if you call nums[5] on an array with 5 elements?
A: It throws an ArrayIndexOutOfBoundsException. The valid indices are 0 through 4.
This connects to Variables and Data Types because every array element must match the declared type. It connects to Functions because arrays can be passed as arguments to methods. It also connects to Classes because objects stored in arrays are instances of a class.
Java strings, string methods, charAt, equals, compareTo, indexOf, length, substring, string concatenation, Java arrays, 1D array, 2D array, multidimensional array, array declaration, array indexing, zero-based index, enhanced for loop, for-each loop, nested for loop, ArrayIndexOutOfBoundsException, out of bounds, CSE 110, ASU, Arizona State, intro Java