Java Arrays and ArrayLists: Lists, Loops and Strings

Learn to store many values in Java and to work with text. Create ArrayLists and arrays, add, change, remove and search their elements, and process them with index loops and for-each loops to compute totals, averages and maximums. Then handle text with String methods: find and cut out parts, split lines into fields, compare strings correctly with equals, and build longer text efficiently with StringBuilder.

BeginnerLesson 4 of 11 in Object-Oriented Programming with Java Course

What you will learn

  1. Create ArrayLists, add, read, replace and remove elements, check what a list contains, and understand what happens when a list is shared or passed to a method.
    • Create a list and work with elements by index
      Import and create an ArrayList, add elements, read and replace them by index, and stay inside the valid index range.
    • Remove elements and check what a list contains
      Remove elements by index or by value, find values with contains and indexOf, and avoid the traps of Integer lists and shifting indexes.
    • Share lists between variables and methods
      Explain what a list variable holds, what happens when a list is assigned or passed to a method, how to copy a list and how to compare two lists.
  2. Create arrays, read and write their elements, pass and copy them correctly, and choose between an array and an ArrayList.
    • Create arrays and access their elements
      Declare and create arrays, fill them, read and write elements by index, and know their length, default values and how to print them.
    • Pass, copy and compare arrays, and choose arrays or lists
      Explain array references, copy and compare arrays correctly, swap elements, and decide when an array or an ArrayList fits the task.
  3. Visit every element with index loops and for-each loops, compute totals, averages and extremes, search for values, and change a list safely while looping over it.
    • Loop through lists and arrays with for and for-each
      Write index loops and for-each loops over lists, arrays and the characters of a string, and choose the right loop for the task.
    • Compute totals, averages, counts and extremes
      Use accumulator variables to compute sums, averages, counts, maximums and minimums, and build a filtered list.
    • Search a list or array for a value
      Write linear searches that return a position, a yes-or-no answer or every match, and search by a condition instead of an exact value.
    • Change a list safely while looping over it
      Remove or add elements during a loop without skipping elements or causing an exception, and choose a safe way to do it.
  4. Treat a string as a sequence of characters, find and extract parts of it, clean it up, and turn lines of text into data and back.
    • Read the characters of a string
      Use length and charAt, loop over characters, work with char values, join text with +, and understand that strings cannot change.
    • Find, extract and clean up parts of a string
      Locate text with indexOf and contains, cut out parts with substring, and change case, spaces and content with replace, trim and related methods.
    • Split text into parts and convert text to numbers
      Break a line into fields with split, convert fields to numbers and numbers to text, check the parts, and join parts back together.
  5. Compare strings by content and by alphabetical order, and use StringBuilder to build and edit text step by step.
    • Compare strings with equals and compareTo
      Use equals and equalsIgnoreCase to test content, avoid the == trap and null errors, and use compareTo to put strings in order.
    • Build and edit text with StringBuilder
      Use StringBuilder to build text in a loop and edit it in place, convert the result to a String, and avoid the common StringBuilder mistakes.

Java Arrays and ArrayLists study guide

5 chapters

1

Store and manage data in an ArrayList

An ArrayList keeps related values in one ordered collection, even when you do not know the final count. Work from creating a typed list to inserting, replacing, removing, and finding elements by index or value. Then follow what happens when two variables or a method share that list, so you can choose between changing existing data and creating a separate result.

1.1 Create and edit an ArrayList

An ArrayList stores values in order. It grows when you add an element and shrinks when you remove one. Each element has an index, starting at 0. Import the class before using it: import java.util.ArrayList;.

Create a typed list
ArrayList<String> drinks = new ArrayList<>();
drinks.add("tea");
drinks.add("milk");

The type inside <String> says what the list stores. The diamond <> on the right lets Java infer that same type. The list starts empty, with size 0; after these two calls it holds [tea, milk] and has size 2. Printing the list directly shows its elements: System.out.println(drinks);.

A list's element type must be a class type. For numbers, use a wrapper class: Integer for int, Double for double, Boolean for boolean, or Character for char. ArrayList<int> will not compile. With ArrayList<Integer> numbers = new ArrayList<>();, numbers.add(5) works because Java boxes the int into an Integer. Reading it into int n = numbers.get(0); unboxes the value.

Follow each index change
String old = drinks.set(0, "coffee");
drinks.add(1, "water");
String last = drinks.get(2);

set(0, "coffee") replaces the first element and returns the old value, so old is "tea". The size stays 2. Inserting "water" at index 1 shifts "milk" right. The list is now [coffee, water, milk]; last is "milk" and the size is 3.

TaskCallValid index
Read an elementget(i)0 through size() - 1
Replace an elementset(i, value)0 through size() - 1
Insert an elementadd(i, value)0 through size()
Append an elementadd(value)No index needed

The extra allowed insertion index is the position just after the current last element. On this list, add(3, "juice") appends, but get(3) would fail before that insertion. An invalid index causes an IndexOutOfBoundsException. Use get(size() - 1) for the last element, after checking that the list is not empty.

Start with data or collect input

With import java.util.List;, new ArrayList<>(List.of("red", "green", "blue")) makes a changeable list containing those values. List.of(...) alone makes an unmodifiable list: add, set, and remove throw UnsupportedOperationException. You will also see List<String> names = new ArrayList<>();; the general List variable still supports these list methods.

To collect lines until an empty line, use a Scanner named scanner and an empty list named lines:

while (true) {
    String line = scanner.nextLine();
    if (line.isEmpty()) {
        break;
    }
    lines.add(line);
}

The stop line is checked before adding, so it is not stored. lines.size() counts the stored lines. lines.isEmpty() tests whether there are none, and lines.clear() removes them all when you need to reuse the list.

Key Takeaways

  • Indexes begin at 0; the last element is at size() - 1.
  • set replaces; indexed add inserts and shifts later elements.
  • Use wrapper types such as Integer in an ArrayList.
  • Copy List.of(...) into an ArrayList when the list must change.
  • clear() removes all elements; an empty list has size 0.

1.2 Remove values and find their positions

Removing an element changes both the size and the indexes of later elements. A search tells you whether a value exists or where it sits now. Keep the difference between a value and its position clear, especially in a list of integers.

Two meanings of remove
CallMeaningResult returned
remove(int index)Remove the element at a positionThe removed element
remove(Object value)Remove the first equal valuetrue if removed; otherwise false

For [coffee, water, milk], remove(0) returns "coffee" and leaves [water, milk]. The old index 2 for "milk" is now invalid; that value has moved to index 1. A saved index is only useful while edits have not changed the positions it describes.

Removing by value does not mean removing every match. Starting with [a, b, a], remove("a") leaves [b, a]. A second call removes the remaining "a". Removing a missing value returns false and leaves the list unchanged, so you can use the result directly:

boolean removed = names.remove("Lena");
if (removed) {
    System.out.println("Name removed");
}
The integer overload trap

An int argument selects the index form, even when the list stores integers:

ArrayList<Integer> numbers = new ArrayList<>(List.of(10, 20, 30));
int removed = numbers.remove(1);
boolean found = numbers.remove(Integer.valueOf(10));

The first call removes index 1, so removed is 20 and the list becomes [10, 30]. The second call explicitly supplies an Integer object. It removes the value 10, makes found true, and leaves [30]. Calling remove(10) on the original three-element list would try index 10 and throw IndexOutOfBoundsException.

Choose a search result

For colors = [red, green, blue, green], contains("green") is true, indexOf("green") is 1, and lastIndexOf("green") is 3. contains gives a yes-or-no answer. The two index methods give the first or last matching position. A missing value produces false or -1, respectively.

These methods use equals to compare elements. String contents must match exactly, including case: indexOf("Green") is -1 for this list. For a case-insensitive search, a loop can compare each name with equalsIgnoreCase.

A match at index 0 is still a match. Testing indexOf(x) > 0 loses it. If you need the position, test the missing marker explicitly:

int index = colors.indexOf("red");
if (index != -1) {
    colors.remove(index);
}

Here the search returns 0, the test succeeds, and removing index 0 leaves [green, blue, green]. To prevent duplicate names, check before adding: if (!names.contains(name)) { names.add(name); }. To remove all occurrences, you can repeat removal while contains is true or use a safe backward loop. A forward loop that always increments after removal can skip a shifted element.

Key Takeaways

  • remove(index) returns an element; remove(value) returns a boolean.
  • For an integer value, use remove(Integer.valueOf(x)).
  • Removal shifts later elements one position left.
  • indexOf and lastIndexOf return -1 for a missing value; 0 means found.
  • String searches are case sensitive and compare contents.
  • Removing by value removes the first match only.

1.3 Understand shared lists and copies

A list variable holds a reference to an object. It does not hold all the elements inside the variable itself. This explains why changing a list through one name can affect another name, and why assigning a parameter has a different effect from editing its elements.

Follow the references
ArrayList<String> original = new ArrayList<>(List.of("tea"));
ArrayList<String> alias = original;
ArrayList<String> copy = new ArrayList<>(original);
alias.add("milk");
copy.add("juice");

original and alias point to one list. After the addition through alias, both show [tea, milk]. The copy is a separate list, created before that addition, so it holds [tea, juice]. Two names for one object are aliases. Assignment copies a reference; the copy constructor creates a new list and copies the elements into it.

The copied list holds references to the same element objects. With strings and wrapper values, those element objects cannot change, so replacing a slot in one list does not change the other list's slot. Copying a list is enough to let these two lists add, remove, and replace independently.

A method gets a copy of the reference

Java passes arguments by value. For a list, that value is a reference. The caller and the parameter initially point to the same list:

static void addBonus(ArrayList<Integer> scores, int bonus) {
    for (int i = 0; i < scores.size(); i++) {
        scores.set(i, scores.get(i) + bonus);
    }
}

Calling addBonus(scores, 5) on [70, 85] changes the caller's list to [75, 90]. The method needs no returned list because it edits the shared object. But assigning scores = new ArrayList<>(); inside the method only redirects its local parameter. The caller's variable still points to the old list.

An int parameter receives a copied number. Changing that parameter cannot change the caller's int variable. In both cases the parameter is local; what differs is whether its value leads to a shared changeable object.

Return new data when that is the task
static ArrayList<String> longWords(ArrayList<String> words, int minLength) {
    ArrayList<String> result = new ArrayList<>();
    for (String word : words) {
        if (word.length() >= minLength) {
            result.add(word);
        }
    }
    return result;
}

The method reads words and writes only to result, so the input stays unchanged. A method that changes an argument should communicate that behavior, as addBonus does. A method that returns new data makes it easier to check the output separately from the input.

Compare contents and handle no results

a == b tests whether two list references point to the same object. a.equals(b) tests equal sizes and equal elements in the same order. Two separately built lists [1, 2] have equal contents but different identities; [2, 1] does not have equal contents in list order.

An empty list is a real object with size 0. A loop over it runs zero times, but get(0) fails because there are no element indexes. null means no list object; even size() then throws NullPointerException. A method with no matches can return an empty result list, letting its caller loop over the result normally.

Key Takeaways

  • Assignment shares a list; new ArrayList<>(original) creates a separate list.
  • A method can edit the caller's list through a copied reference.
  • Reassigning a parameter does not redirect the caller's variable.
  • List equals compares ordered contents; == compares identity.
  • An empty list supports iteration; null refers to no list.
2

Store fixed-size data in arrays

Arrays give each value a numbered slot in a structure whose length stays fixed. Create and fill those slots, read their default values, and print their contents clearly. Copying, comparing, swapping, and passing arrays to methods all depend on understanding which variables refer to the same object. Use these ideas to choose an array or an ArrayList for a particular task.

2.1 Create arrays with fixed slots

An array stores a fixed number of elements of one type. You choose its length when creating it. Elements can change, but the number of slots in that array cannot. Arrays can store primitive values directly.

Create and fill slots
int[] scores = new int[5];
scores[0] = 90;
int first = scores[0];
int[] primes = {2, 3, 5, 7, 11};

new int[5] creates five slots. Their indexes are 0, 1, 2, 3, and 4. Square brackets read and write a slot, so first becomes 90. The initializer for primes both creates and fills five slots. When a filled array is needed as an expression, such as a method argument, use new int[] {2, 3, 5}.

The length is a field: scores.length, with no parentheses. It counts all slots, including ones you have not assigned yourself. Adding a value to slot 0 does not change the length from 5 to 1.

StructureNumber of elementsRead an element
Arraya.lengtha[i]
ArrayLista.size()a.get(i)
Strings.length()s.charAt(i)

These names are not interchangeable. An array has no size() method, and a string needs parentheses after length.

Know the starting values

New array slots receive defaults. Numeric primitive arrays start with zero: 0 for int, 0.0 for double. A boolean[] starts with false; a char[] starts with the character whose code is zero, written '\u0000'. Arrays of class types, including String[], start with null references.

String[] words = new String[3];
words[0] = "sun";
System.out.println(words[0].length());

This prints 3 because slot 0 now refers to "sun". Slots 1 and 2 still hold null. Calling words[1].length() throws NullPointerException: there is no string there yet. A default null slot is different from an empty string "", which is an object with length 0.

Read output and stay inside the array

Import java.util.Arrays and use System.out.println(Arrays.toString(scores)); to print [90, 0, 0, 0, 0]. Printing scores directly shows a type and identity code such as [I@1b6d3586, not its elements. The identity code is not a useful report of the stored numbers.

For one week of temperatures in degrees Celsius:

double[] temps = {12.5, 14.0, 9.5, 11.0, 15.5, 13.0, 10.5};
temps[2] = 10.0;

The third day's reading changes from 9.5 to 10.0. The first reading is temps[0]; the last is temps[6], or temps[temps.length - 1]. temps[7] is outside the array. Java throws ArrayIndexOutOfBoundsException for an invalid array index. In an index loop, use i < temps.length: i <= temps.length tries one extra slot after the last valid one. A zero-length array has no valid element indexes at all.

Key Takeaways

  • Array length is fixed when the array is created.
  • Use a[i] to read or write a slot and a.length to count slots.
  • New numeric slots contain zero; new String slots contain null.
  • Arrays.toString(a) prints contents.
  • The last valid index is a.length - 1.

2.2 Copy, compare, and swap array elements

An array variable holds a reference, just as a list variable does. Assigning that reference creates another name for the same array. A separate copy needs a new array object, and comparing contents needs a method that checks the slots.

Assignment and copying
int[] a = {4, 9, 2};
int[] alias = a;
int[] copy = Arrays.copyOf(a, a.length);
alias[0] = 99;

Now a and alias both show [99, 9, 2]; copy still shows [4, 9, 2]. Arrays.copyOf(a, a.length) makes a new array of the same length. a.clone() can also copy it. Import java.util.Arrays for the utility methods.

A different requested length changes the new array, not the old one. Arrays.copyOf(new int[] {2, 3, 5}, 4) yields [2, 3, 5, 0]. Extra slots receive default values. To let a variable refer to a larger array, assign the returned copy to that variable. Any alias of the original still refers to the old array.

Method calls share the object
static void doubleAll(int[] values) {
    for (int i = 0; i < values.length; i++) {
        values[i] = values[i] * 2;
    }
}

The parameter receives a copy of the reference. The method therefore changes the caller's array slots. Reassigning values to a new array would change only the parameter. A method can return a new array instead: return new int[] {values[0], values[values.length - 1]}; produces [4, 2] for input {4, 9, 2}. That expression needs a nonempty input because it reads two indexes.

Content equality is different for arrays

For separately created arrays a = {1, 2} and b = {1, 2}, both a == b and a.equals(b) are false: array equals checks identity. Arrays.equals(a, b) is true because the corresponding elements match. This differs from ArrayList, whose equals compares ordered contents.

Save a value before overwriting it

To exchange two positions, keep one old value in a temporary variable:

int temp = a[0];
a[0] = a[2];
a[2] = temp;

Starting with {4, 9, 2}, the first line saves 4. The second produces [2, 9, 2]. The third restores the saved 4 at index 2, completing [2, 9, 4]. Without temp, assigning a[2] = a[0] after the second line would copy 2 again and lose the original 4.

Choose a structure that fits the data
NeedSuitable choice
A fixed slot for each day or monthArray
Primitive values without wrappersArray
Add or remove elements as input arrivesArrayList

Arrays also appear in main(String[] args) and as the result of String.split. For a String[] words, new ArrayList<>(Arrays.asList(words)) makes a list that can grow. For an int[], create an ArrayList<Integer> and add each integer in a loop. Arrays.asList on the primitive array treats the whole array as one element, so it does not make a list of its individual numbers.

Key Takeaways

  • Array assignment shares the same object; copyOf or clone creates a copy.
  • Use Arrays.equals for array contents.
  • A method can change shared array slots through its parameter.
  • A temporary variable preserves a value during a swap.
  • Use arrays for fixed slots and ArrayLists for changing counts.
  • Convert a primitive array to a wrapper list with a loop.
3

Process lists and arrays with loops

Loops turn stored values into useful results: a total, a count, an extreme, a filtered collection, or a search result. Choose how to visit elements according to whether you need values or positions. Follow each loop's changing state to handle empty data, preserve fractional averages, stop a search at the right time, and remove values without missing the elements that shift.

3.1 Choose an index loop or a for-each loop

A loop lets one piece of code process every element. The choice depends on what the body needs: just a value, its position, or a way to write back to the collection. Both arrays and ArrayLists support index loops and for-each loops.

Visit values in order
for (String task : tasks) {
    System.out.println(task);
}

Read this as “for each task in tasks.” With [shop, cook, clean], it prints the three strings in that order. The loop variable has the element type. For ArrayList<Integer>, use int to unbox each value or Integer to keep the wrapper reference. For string characters, for (char c : word.toCharArray()) visits the char values.

A for-each loop does not provide an index. If you need numbered lines, use an index loop:

for (int i = 0; i < tasks.size(); i++) {
    System.out.println((i + 1) + ". " + tasks.get(i));
}

The index starts at 0, but the displayed line number starts at 1. Parentheses make i + 1 an addition before it becomes part of the text. For an array, change the condition to i < tasks.length and read tasks[i]. A while loop can do the same work by initializing a counter before the loop and incrementing it in the body.

Write back through a position
int[] nums = {4, 9, 2};
for (int n : nums) {
    n = n * 2;
}

This leaves the array unchanged. Each pass puts a copy of one primitive value in n; assigning to that local variable does not write to the original slot. To change the array:

for (int i = 0; i < nums.length; i++) {
    nums[i] = nums[i] * 2;
}

The result is [8, 18, 4]. For an integer list, the corresponding update is list.set(i, list.get(i) * 2). The index tells Java which stored element to replace.

Make the bounds fit the body

For a backward list traversal, start at tasks.size() - 1, continue while i >= 0, and use i--. This visits clean, cook, then shop. Taking every second element can use i += 2 in a forward loop.

Neighbor comparisons need a shorter range. If the body reads both list.get(i) and list.get(i + 1), the condition is i < list.size() - 1. The final valid starting position is the next-to-last element. Using the usual full traversal condition would try to read a nonexistent neighbor after the last element.

When processing two same-length lists together, use one index to access both. For example, names.get(i) and scores.get(i) describe the corresponding entries. A for-each loop is simpler when the position has no role, such as printing every name or adding every value to a total.

Starting at 1 silently skips the first element. Using <= size() or <= length tries one invalid extra index. An empty list or array needs no special traversal rule: the initial condition is false, so the body runs zero times. Any later code that divides by the count or reads an element must handle that empty case itself.

Key Takeaways

  • For-each is useful when the body only needs each value.
  • Use an index to write stored values, track positions, or compare neighbors.
  • Assigning a for-each variable does not replace an array or list element.
  • Neighbor access at i + 1 needs i < size() - 1.
  • Empty collections make a normal traversal run zero times.

3.2 Compute a result from many elements

An accumulator keeps a result built across loop passes. Initialize it before the loop, update it inside, and use it afterward. The starting value depends on the task: a sum or count starts at 0, while a maximum needs an actual element.

Totals and averages
int sum = 0;
for (int value : numbers) {
    sum += value;
}
if (!numbers.isEmpty()) {
    double average = (double) sum / numbers.size();
    System.out.println(average);
}

For [4, 7, 8], sum changes from 0 to 4, then 11, then 19. Both operands in sum / numbers.size() would be integers, giving 6. Casting sum before the division gives about 6.33. Casting the already computed quotient would only turn the truncated 6 into 6.0.

An empty collection has no ordinary average. Integer division by zero throws ArithmeticException; floating-point 0.0 / 0 gives NaN. Decide what the empty case means for the program before dividing, such as displaying “No measurements.” For decimal distances [5.0, 7.5, 10.0] km, a double total is 22.5 km and the average is 7.5 km.

Count only matches

A conditional count starts at 0 and increments only when its test succeeds. For temperatures {22, 27, 31, 24, 26} degrees Celsius, if (t > 25) { count++; } produces 3. Put the initialization outside the loop; resetting count on every pass would discard previous matches.

Find an extreme and its position

For a nonempty array, start int max = values[0];. Replace max whenever a visited value is greater. Starting at 0 fails on {-5, -2, -9}: it reports 0 even though no element has that value. Starting with -5 lets the loop reach the correct maximum, -2. A minimum uses the same pattern with <.

When the position matters, keep the best index:

int best = 0;
for (int i = 1; i < numbers.size(); i++) {
    if (numbers.get(i) > numbers.get(best)) {
        best = i;
    }
}

For [4, 7, 8], best ends at 2, and numbers.get(best) is 8. The loop begins at 1 because index 0 is already the initial candidate. With >, an equal value does not replace the current candidate, preserving the first maximum. With >=, each tie replaces it, preserving the last maximum. Check for an empty collection before creating a candidate at index 0.

Collect matching values

Filtering uses an empty result list as the accumulator. Visit every word, add it when word.length() > 4, and return the result. For [sun, planet, moon, galaxy], the result is [planet, galaxy]. Reading the input and adding to a separate list leaves the input unchanged.

For two Integer elements, == compares object identity. Cached small values can hide this error; equal larger values can be different objects. Compare with equals, or unbox into int variables first. Numeric <, >, <=, and >= unbox wrapper values, so the best-index code compares their numbers.

Key Takeaways

  • Initialize an accumulator before the loop and update it inside.
  • Cast before integer division to retain the fractional part of an average.
  • Check for emptiness before averaging or selecting an extreme.
  • Initialize a maximum or minimum from an actual element.
  • > preserves the first maximum; >= preserves the last.
  • Filtering accumulates matches in a new list.
  • Use value equality for two Integer objects.

3.3 Search until a match or the end

A linear search checks elements in sequence. It works on data in any order. A successful first-match search can stop early; an unsuccessful search must reach the end before it knows that no element matches.

Return the first matching index
static int indexOfName(ArrayList<String> names, String target) {
    for (int i = 0; i < names.size(); i++) {
        if (names.get(i).equals(target)) {
            return i;
        }
    }
    return -1;
}

If the first matching name is at index 2, the method checks indexes 0, 1, and 2, then returns 2 immediately. The return -1 is after the loop because only a completed traversal establishes failure. Putting else { return -1; } inside would stop on the first nonmatching element and ignore every later candidate.

The missing marker -1 cannot be a valid index. The caller must check it before reading the result:

int index = indexOfName(names, "Ahmed");
if (index != -1) {
    System.out.println(names.get(index));
}

Testing index > 0 would miss a valid match at index 0. Using -1 directly in get would throw an exception. On an empty list the loop body never runs, and the method correctly returns -1.

Change the comparison to fit the task

For exact list values, contains and indexOf already do a linear search. Write a loop for an array or a condition such as “starts with L.” Use equals or equalsIgnoreCase for strings, == for primitives, and equals for two Integer objects. A string identity test can miss equal text.

For String[] cities = {"Oslo", "Lima", "Lagos", "Pune"}, test cities[i].startsWith("L"). Index 0 fails; index 1 succeeds, so the first-match result is 1. If the task asks for every match, do not return there. Append matching indexes to a result list and finish the traversal; that gives [1, 2]. To count matches, increment a counter instead of storing positions.

Choose the shape of the answer

A yes-or-no search can start with boolean found = false;. On a match, set it to true and break out of the loop. Without the break, the final answer stays true but the program checks values it no longer needs. A search method can also return true immediately and return false after the loop.

Returning an element needs a separate “nothing found” result. For a String, this is often null; the caller must check it before calling a String method. Returning an index with -1 makes the missing case visible without claiming that an empty string is absent data.

Count the work the search actually does

A target at the first position requires one comparison. A target at the third position requires three. A missing target in 10,000 names requires all 10,000 comparisons. The first failed comparison cannot establish that the target is missing from the remaining positions. An all-matches search also checks every element, even after an early match, because later values can match too.

Key Takeaways

  • Linear search visits elements in sequence and works in any input order.
  • Return an index at the first match; return -1 only after the loop.
  • Use the comparison appropriate to the element type.
  • All-matches searches keep scanning after a match.
  • Check a missing marker before using the search result.

3.4 Remove elements without skipping them

Removing from an ArrayList changes the positions that a loop is trying to visit. The safe pattern depends on whether you need to change the original list or build a separate result. Replacing values is simpler because it leaves the positions in place.

See how a forward loop skips a value

Suppose a loop removes even numbers from [3, 8, 8, 5] and always increments i. At index 1 it removes the first 8. The second 8 slides into index 1, but the next pass uses index 2. The result is [3, 8, 5], with one even number left. The condition was correct; the movement after removal was wrong.

A for-each loop over an ArrayList also must not add or remove through the list. It uses an iterator whose traversal state no longer matches the edited list. Java usually reports ConcurrentModificationException. Some edits can instead end the loop quietly, leaving an element unvisited. The absence of an exception does not make that edit safe.

Remove backward to keep unchecked positions stable
for (int i = numbers.size() - 1; i >= 0; i--) {
    if (numbers.get(i) % 2 == 0) {
        numbers.remove(i);
    }
}

For [3, 8, 8, 5], index 3 contains 5 and stays. Index 2 contains 8 and is removed. Index 1 still contains the other 8 and is removed next. Index 0 contains 3 and stays. The result is [3, 5]. A removal shifts elements to the right of the current index, which this backward loop has already checked.

Build the values to keep

When the original should stay unchanged, create a new list:

ArrayList<Integer> odds = new ArrayList<>();
for (int value : numbers) {
    if (value % 2 != 0) {
        odds.add(value);
    }
}

This for-each loop is safe because it reads numbers and adds to a different list. With [3, 8, 8, 5] as input, odds holds [3, 5] and the input still holds all four values. An array cannot shrink either; filtering its values also needs a new array or list.

Let an iterator manage its own removal
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
    if (it.next() % 2 == 0) {
        it.remove();
    }
}

Import java.util.Iterator. next() supplies the next element, and it.remove() removes the element just returned while keeping the iterator's position consistent. Do not substitute numbers.remove(...) in this loop.

A forward while loop can also work by incrementing only when nothing was removed. After removal it must inspect the same index again, where the next element has arrived. This needs more care than a backward loop or a new result list.

Replacements and additions have different effects

set(i, value) is safe in an index loop because it changes no size or position. Adding on every pass while testing i < list.size() can keep moving the end away forever. Save int originalSize = list.size(); and loop only to that bound when each original element should cause one appended value.

Key Takeaways

  • Forward removal followed by i++ skips the element shifted into the removed slot.
  • A backward loop can remove by index safely.
  • Filtering into another list preserves the original.
  • Use an iterator's own remove during iterator traversal.
  • For-each traversal must not add or remove through its source list.
  • Bound append loops by the original size when processing original elements only.
4

Work with text using String methods

Text arrives as characters, but a program often needs names, numbers, or selected parts of a line. Read positions with String methods, find a separator before cutting text, and turn separated fields into values you can calculate with. Keep track of the returned results: strings are immutable, and cleaning a string only helps later code when that code uses the cleaned text.

4.1 Read characters and keep String results

A String stores text as a sequence of char values. Indexes start at 0, just as they do for arrays and lists. A String object cannot change after creation, so methods that produce changed text return a result you need to keep.

A character is different from a string

"Hello".length() is 5. "Hello".charAt(0) is 'H' and charAt(4) is 'o'. A char uses single quotes and holds one UTF-16 code unit; a String uses double quotes and can hold zero, one, or many of those units. "Java".charAt(0) == 'J' compares two primitive characters. Comparing that char with "J" does not compile because the types differ.

charAt(length()) is past the end and throws StringIndexOutOfBoundsException. Even charAt(0) fails for "". Check isEmpty() before reading the first character of input.

length() counts UTF-16 char values, which are not always whole displayed symbols. "café".length() is 4; "Hi 👋".length() is 5 because the waving-hand emoji occupies two char positions. Use that count when reasoning about these methods' indexes.

Visit and test the characters
String text = "Programming in Java".toLowerCase();
int vowels = 0;
for (int i = 0; i < text.length(); i++) {
    char c = text.charAt(i);
    if ("aeiou".indexOf(c) >= 0) {
        vowels++;
    }
}

The lowercase conversion lets the same membership test recognize uppercase and lowercase vowels. Each indexOf(c) is nonnegative when the character appears in "aeiou". The count reaches 6: o, a, i, i, a, a. for (char c : text.toCharArray()) can visit the same values without an index.

The Character class supplies tests such as isLetter, isDigit, isWhitespace, and isUpperCase. Character.isDigit('7') is true, while Character.isLetter('7') is false. Character.toUpperCase(c) and toLowerCase(c) return converted char values.

Characters also have numeric codes. 'a' + 1 produces the int 98; (char) ('a' + 1) converts that code to 'b'. For an ASCII digit character, subtracting '0' gives its value: '7' - '0' is 7. Subtracting the code for zero works because those digit codes are consecutive.

Read concatenation from left to right
ExpressionResult
"Total: " + 3 + 4"Total: 34"
3 + 4 + " items""7 items"
"Total: " + (3 + 4)"Total: 7"

Once the left side of + is text, the next number is joined as text. Parentheses force the numeric addition before joining. A few joins in one expression are a clear use of +.

Save the returned text
String name = "Lena";
name.toUpperCase();
System.out.println(name);
name = name.toUpperCase();

The print still shows "Lena": the discarded call did not change its object. The assignment then makes name refer to "LENA". String immutability means the old text remains unchanged even if other variables refer to it. Keeping the result and changing the original object are different operations.

Key Takeaways

  • charAt(i) returns a char; valid indexes end at length() - 1.
  • Chars use single quotes; strings use double quotes.
  • String length counts UTF-16 char values, so some symbols occupy two positions.
  • Character methods test and convert single char values.
  • String joining with + proceeds left to right.
  • Store the result of a String transformation.

4.2 Find and extract parts of text

Text processing often follows a short sequence: find a marker, check that it exists, then extract the part you need. Cleaning operations can prepare the text before a search or comparison. Each String operation returns a result without changing its original object.

Find positions or ask a yes-or-no question

For "banana", indexOf('a') returns 1, indexOf("a", 2) returns 3, and lastIndexOf('a') returns 5. The second argument chooses where the forward search begins. A missing search gives -1, as in indexOf("x").

Use contains(text) when you only need to know whether text appears. startsWith(prefix) checks the beginning and endsWith(suffix) the end. "report.pdf".endsWith(".pdf") is true. These searches are case sensitive: "Hello".contains("hello") is false. The index methods accept a char or a String; contains takes text.

Substring ends just before its end index
String word = "programming";
String middle = word.substring(3, 7);
String tail = word.substring(3);

middle is "gram", using positions 3, 4, 5, and 6. Its length is 7 - 3, or 4. tail is "gramming", because omitting the end argument runs to the string's end. The beginning must be nonnegative and no greater than the end; the end cannot exceed length(). Invalid bounds throw StringIndexOutOfBoundsException.

For an email address, find the separator before slicing:

String email = "lena.ito@example.com";
int at = email.indexOf("@");
if (at != -1) {
    String user = email.substring(0, at);
    String domain = email.substring(at + 1);
}

The separator is at index 8. The first slice ends before it, giving "lena.ito"; the second begins after it, giving "example.com". If the marker is absent, at is -1. Calling substring(0, at) without the check would fail. Starting the second slice at at would keep the @ in the domain.

Clean only what the operation targets
MethodEffect
toUpperCase() / toLowerCase()Return text with converted letter case
trim()Remove leading and trailing characters with codes through U+0020
strip()Remove leading and trailing whitespace recognized by Character.isWhitespace
replace(target, replacement)Replace every literal occurrence
repeat(n)Join n copies of the text

" hello ".trim() gives "hello"; inner spaces stay. strip() handles additional Unicode whitespace such as an em space. It uses Java's whitespace definition, which does not include every character that looks like a space. "banana".replace('a', 'o') gives "bonono". "ab".repeat(3) gives "ababab".

Empty and blank are different

isEmpty() tests length 0. isBlank() also accepts text consisting only of Java whitespace. For " ", the first is false and the second true. Use the test that matches the input rule. To clean an answer like " Yes ", answer.trim().toLowerCase() returns "yes". Store that returned text if the variable should keep the cleaned value; a standalone answer.trim(); discards it.

Key Takeaways

  • Position searches return -1 when a marker is missing.
  • substring(begin, end) includes begin and excludes end.
  • Check a found position before using it as a slice boundary.
  • replace replaces literal text; trim and strip act at the ends.
  • isBlank accepts whitespace-only text, while isEmpty needs length 0.

4.3 Turn a line of text into usable fields

A data line can contain several values separated by a comma or another marker. Splitting produces an array of strings; parsing then converts selected fields into numbers. Check the shape of the data before using its positions.

Split into an array
String[] fields = "Ada,36,London".split(",");

There are three fields: "Ada", "36", and "London". The commas are not kept. fields.length is 3, and fields[1] is still text, not a number.

The separator passed to split is a regular expression, a pattern rather than always literal text. A comma means itself, but ., |, *, +, and ? have special meanings. To split a version string at literal dots, use "1.5.2".split("\\."). Two backslashes in the Java string produce the one pattern backslash that makes the dot literal. split(".") instead matches individual characters and produces an empty array for this example.

Handle spaces and empty pieces

Splitting "a b" at " " produces three pieces: "a", "", and "b". Each separator is one space, so adjacent spaces leave an empty piece between them. For runs of whitespace, use:

String[] words = "  red   green blue ".trim().split("\\s+");

The result is [red, green, blue]. Trimming first avoids an empty initial piece from a leading separator. Default split drops trailing empty pieces: "a,b,,".split(",") yields only "a" and "b". Count the actual resulting fields before indexing them.

Parse each field into its intended type

Integer.parseInt("42") returns the primitive int 42. Integer.valueOf("-7") returns an Integer object. Double.parseDouble("5.2") returns 5.2, using a period for the decimal separator regardless of the computer's country settings. Integer parsing accepts integer text without a decimal point. Integer.parseInt("4.5") fails instead of rounding.

Trim fields before parsing, especially integer text: Integer.parseInt(" 42") throws NumberFormatException. Splitting at commas does not remove spaces around the fields. A correct field count also does not guarantee that a field contains a valid number.

Read a complete record
String line = "Amira,10.5,63";
String[] parts = line.split(",");
if (parts.length == 3) {
    String name = parts[0].trim();
    double distanceKm = Double.parseDouble(parts[1].trim());
    int minutes = Integer.parseInt(parts[2].trim());
    double pace = minutes / distanceKm;
    System.out.println(name + ": " + pace + " min/km");
}

The distance is 10.5 km, the time is 63 minutes, and the pace is 6.0 min/km. The incomplete line "Amira,10.5" has only two fields; without the count check, parts[2] would throw ArrayIndexOutOfBoundsException. A program can skip or report that incomplete record before using any missing position.

Convert or join text again

String.valueOf(42) and Integer.toString(42) both give "42". String.join(", ", List.of("Oslo", "Lima", "Pune")) gives "Oslo, Lima, Pune", inserting separators only between parts. It accepts a list, an array, or separate string arguments. Joining does not parse or calculate: it combines the supplied strings.

Key Takeaways

  • split returns a String array and treats its separator as a pattern.
  • Escape a literal dot as "\." in Java code.
  • Trim before splitting whitespace runs and before parsing integer fields.
  • Default split drops trailing empty fields.
  • Check field count and numeric text before using parsed data.
  • Use String.join for text parts and parsing methods for numbers.
5

Compare strings correctly and build text efficiently

Equal-looking text can belong to different String objects. Choose a comparison that matches the task: content equality, equality ignoring case, or Java's character ordering. Then build and edit larger pieces of text with StringBuilder. Following both references and returned values helps you predict whether an operation changes existing text, creates a result, or merely compares two objects.

5.1 Compare string contents and ordering

Two variables can hold text with the same characters without referring to the same String object. Choose a comparison based on the question: equal contents, equal contents ignoring case, or which text comes first in Java's ordering.

Use equals for contents
String answer = new String("yes");
System.out.println(answer == "yes");
System.out.println(answer.equals("yes"));

The first result is false: the separately created object is not the literal's object. The second is true because the characters match. Identical literals such as "yes" == "yes" share an object and can make identity comparison seem reliable. Runtime text may use new or existing objects, so identity is not the test for matching input.

equalsIgnoreCase ignores letter case: "YES".equalsIgnoreCase("yes") is true. It does not remove spaces. To accept surrounding spaces too, clean the input before comparing.

For a variable that might be null, call from a known non-null literal: "yes".equals(answer) returns false for null. answer.equals("yes") throws NullPointerException if answer is null, because no object receives the call.

A command loop can test !command.equals("quit"). The ! negates content equality. command != "quit" tests references instead and can keep a loop running even when the typed characters say “quit.”

Interpret the sign of compareTo

a.compareTo(b) compares UTF-16 char values in sequence. It returns a negative number if a comes before b, zero if equal, and a positive number if after. Only the sign matters for ordering; a result need not be exactly -1 or 1.

ComparisonSignReason
"apple".compareTo("banana")NegativeFirst differing char is earlier
"pear".compareTo("pear")ZeroAll characters match
"car".compareTo("carpet")NegativeEqual prefix, shorter string first
"10".compareTo("9")Negative'1' comes before '9'

Numbers stored as text therefore do not follow numeric order. Parse them when the task is numeric. Unaccented uppercase English letters precede unaccented lowercase letters, so "Zebra" comes before "apple". Accented "Émile" comes after "Zoe" in this ordering. compareToIgnoreCase ignores case; language-specific dictionary ordering needs java.text.Collator.

Reuse the minimum pattern for names

For a nonempty list [Mia, Ahmed, Lucia]:

String first = names.get(0);
for (String name : names) {
    if (name.compareTo(first) < 0) {
        first = name;
    }
}

"Mia" starts as the candidate. "Ahmed" compares before it and becomes the candidate; "Lucia" does not replace it. The result is "Ahmed". Check for an empty list before reading its first element.

A single char is a primitive, so word.charAt(0) == 'A' is a correct character comparison once the word is known to be nonempty. The problem with == concerns object identity, not every comparison involving text.

Key Takeaways

  • Use equals for String contents and equalsIgnoreCase to ignore case.
  • A known literal can safely receive equals when the argument might be null.
  • == checks String identity, even when literal sharing hides the mistake.
  • Read only the sign of compareTo.
  • Java string ordering is UTF-16 ordering, not numeric or language-specific dictionary order.

5.2 Build and edit text with StringBuilder

A StringBuilder holds changeable text. It is useful when a loop adds many pieces or when characters need editing in place. A few joins in one expression are clear with +, but repeatedly rebuilding a growing String can copy its accumulated contents many times.

Append pieces and finish with a String
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
    if (i > 1) {
        sb.append(", ");
    }
    sb.append(i);
}
String result = sb.toString();

No import is needed. append adds strings, chars, numbers, or booleans to the end. The first pass adds just 1; the second adds ", " then 2. The result is "1, 2, 3, 4, 5". Putting a separator after every number would leave an unwanted separator at the end. For an existing list of strings, String.join(", ", list) handles separators directly.

Repeated text += piece in a loop forms new immutable String results. The accumulated prefix has to be included each time, so the amount copied can grow quadratically as a long result grows. A builder keeps a changeable buffer and appends to it without rebuilding the whole prefix on every pass.

Edit positions and ranges
MethodEffect
insert(i, x)Insert at position i
delete(start, end)Remove a range, excluding end
deleteCharAt(i)Remove one char
setCharAt(i, c)Replace one char
replace(start, end, text)Replace a range, excluding end
reverse()Reverse the builder's order

length() and charAt(i) read the builder as they do a String. Indexes describe its current state; an insertion or deletion can change later positions.

Start with new StringBuilder("Jva"). insert(1, 'a') produces "Java"; setCharAt(0, 'j') then gives "java". For "2026-10-22", delete(4, 7) removes positions 4, 5, and 6, leaving "2026-22". Replacing positions 7 through 9 in "I like tea" with "coffee" gives "I like coffee".

Chain only methods that return the builder

new StringBuilder().append("a").append(1).append('b').toString() gives "a1b". The append calls return the same builder, allowing another call. The editing methods here also return the builder except setCharAt, which returns void and needs a separate statement.

reverse() changes the receiver. If sb holds "stressed", then String r = sb.reverse().toString(); leaves both r and the builder's text as "desserts". To preserve the original builder, reverse a new builder created from its text.

Compare finished contents

For a palindrome check, append the lowercase form of every letter in "Was it a car or a cat I saw". The cleaned text is "wasitacaroracatisaw". Reverse a new builder holding that text, convert it to a String, and compare with clean.equals(reversed). The comparison is true.

StringBuilder does not override equals to compare contents. Separate builders holding "abc" are not equal by that method, and a builder is not equal to a String. Convert first: sb1.toString().equals(sb2.toString()) compares the actual text.

Key Takeaways

  • Use append to build a long result and toString to finish it.
  • Put separators between values, avoiding an extra final separator.
  • Builder edits change the existing builder; range ends are excluded.
  • setCharAt returns void, so it cannot be chained.
  • reverse changes the builder you call it on.
  • Convert builders to Strings before comparing contents.

Java Arrays and ArrayLists examples

5 Walkthroughs

1

Build and share a reading list

13 steps
Create a list, follow changes to its positions, and decide which edits are shared by another variable.
  1. 1
    IntroductionTrack a changing reading list

    A reading list can start empty and grow as suggestions arrive. You will add titles, correct one entry, remove a duplicate, and pass the list to a method. Keep two questions separate as you trace the code: which element occupies each index now, and which variables refer to the same list object? The first explains position changes; the second explains shared edits.

  2. 2
    ExplanationCreate the empty collection

    Import java.util.ArrayList, then create the list:

    ArrayList<String> reading = new ArrayList<>();
    reading.add("Orbit");
    reading.add("River");
    

    The element type is String. The empty list grows to size 2 and contains [Orbit, River]. Index 0 identifies Orbit and index 1 identifies River. The diamond <> lets Java infer the element type from the left side.

  3. 3
    ExampleInsert before a stored title

    Continue with the same list:

    reading.add(1, "Cloud");
    String old = reading.set(2, "Forest");
    

    Insertion shifts River from index 1 to index 2, giving [Orbit, Cloud, River]. The replacement then changes index 2 to Forest and returns River into old. The final list is [Orbit, Cloud, Forest]. Unlike insertion, replacement has not changed the size.

  4. 4
    ChallengeFind the next valid position

    The list is [Orbit, Cloud, Forest]. What happens if you call reading.add(3, "Dune")? What would reading.get(3) return afterward?

    ---reveal---

    The insertion appends Dune because index size() is allowed for insertion. The size becomes 4, so index 3 is now a valid read and returns "Dune". Reading index 3 before the insertion would have failed.

  5. 5
    ExplanationRemove one value and follow the shift

    Add another Cloud, then remove by value:

    reading.add("Cloud");
    boolean removed = reading.remove("Cloud");
    

    The list before removal is [Orbit, Cloud, Forest, Dune, Cloud]. Only the first Cloud is removed, so the result is [Orbit, Forest, Dune, Cloud] and removed is true. Forest and every later element move one position left. The final Cloud remains in the list.

  6. 6
    TipAsk whether or where

    For [Orbit, Forest, Dune, Cloud], contains("Orbit") is true and indexOf("Orbit") is 0. A found test must accept index 0: use index != -1 after saving the search result. A missing title returns -1. Searches compare String contents with case sensitivity, so searching for "orbit" does not find "Orbit". Use lastIndexOf when the last matching position matters.

  7. 7
    ChallengeRemove a number by its meaning

    A separate ArrayList<Integer> holds [9, 1, 9]. You want to remove the first value 9. What call works, and what remains?

    ---reveal---

    numbers.remove(Integer.valueOf(9)) selects removal by value and leaves [1, 9]. remove(9) would select index 9, which is invalid. The primitive int selects an index even though the list itself stores integers.

  8. 8
    AnalogyTwo names on one notebook

    Think of a reference like a note saying where one notebook is kept. Copying the note does not create another notebook. With ArrayList<String> shared = reading;, both variables identify one list, so shared.add("Coast") is visible through reading. A copy constructor, new ArrayList<>(reading), instead creates another list with its own slots.

  9. 9
    ExampleCopy before changing

    Start from [Orbit, Forest, Dune, Cloud]:

    ArrayList<String> copy = new ArrayList<>(reading);
    copy.remove("Dune");
    

    The copy becomes [Orbit, Forest, Cloud], while reading stays unchanged. Both lists initially referred to the same immutable String elements, but their list slots are separate. Removing a slot from one does not remove it from the other.

  10. 10
    Key InsightA parameter is another local name

    A method receives a copy of a list reference. Calling titles.clear() through that parameter changes the shared list. Assigning titles = new ArrayList<>(); changes only the local name, so the caller keeps its old list. An empty list is still an object; null is no object. Calling size() on empty returns 0, while calling it through null fails.

  11. 11
    ChallengeSeparate shared edits from local reassignment

    A caller list is [North, South]. The method runs these statements:

    titles.remove("North");
    titles = new ArrayList<>();
    titles.add("East");
    

    What does the caller still see?

    ---reveal---

    It sees [South]. Removal edits the shared object first. Reassignment then redirects only the method parameter, so East is added to a different list. The caller's reference was never redirected.

  12. 12
    ChallengeCombine a copy, search, and edit

    Let a hold [Lake, Hill], then run b = new ArrayList<>(a), b.add("Lake"), and b.remove(b.indexOf("Lake")). What do a and b contain, and does a.equals(b) return true?

    ---reveal---

    The search returns index 0, so b becomes [Hill, Lake]. The original a stays [Lake, Hill]. The sizes match but the order differs, so list equals returns false.

  13. 13
    RecapPredict a list change

    Read an edit by identifying its target first: a position for set or indexed removal, a value for value removal, and an insertion position for add. Then update shifted indexes before tracing the next call. To predict what another variable sees, follow whether it shares the list or holds a separate copy. Method reassignment affects its parameter; edits affect the object that parameter currently reaches.

2

Store and copy fixed readings

10 steps
Use fixed array slots, inspect default values, and preserve data during copying and swapping.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive each reading a fixed slot
  2. 2
    ExplanationAllocate the slots
  3. 3
    ExamplePrint the data you need
  4. 4
    ChallengeRead the final slot
  5. 5
    ExampleFollow an alias
  6. 6
    ExampleCreate a larger copy
  7. 7
    ChallengeChoose a content comparison
  8. 8
    ExampleSave before overwriting
  9. 9
    ChallengeKeep old data while expanding
  10. 10
    RecapSeparate slot edits from new storage
3

Turn readings into results

17 steps
Trace loop state, calculate an average, search by a condition, and remove unwanted values safely.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionGive each loop one clear job
  2. 2
    ExplanationRead values or read positions
  3. 3
    ChallengeLeave room for a neighbor
  4. 4
    ExampleCarry a sum across the loop
  5. 5
    ExampleDivide after keeping the fraction
  6. 6
    Key InsightAn extreme needs a real candidate
  7. 7
    ChallengeTrack the last tied maximum
  8. 8
    ExplanationStop only when the answer is known
  9. 9
    ExampleFind the first reading above a limit
  10. 10
    ChallengeChange from first match to all matches
  11. 11
    ExampleWatch a forward deletion skip
  12. 12
    ExplanationWalk backward for removal
  13. 13
    ConnectionKeep the source by filtering
  14. 14
    TipUse the iterator that owns the traversal
  15. 15
    ChallengeBound a loop that appends
  16. 16
    ChallengeAverage only the selected values
  17. 17
    RecapTrace state and stopping rules
4

Read a text record in stages

14 steps
Inspect characters, extract a labeled part, and split a record into numeric fields.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFrom raw text to data
  2. 2
    ExplanationRead one character at a time
  3. 3
    ExampleCount digits in a label
  4. 4
    ChallengeKeep a transformation
  5. 5
    ExplanationLocate a boundary first
  6. 6
    ExampleCount the included positions
  7. 7
    TipChoose the cleanup rule
  8. 8
    ChallengeHandle a missing separator
  9. 9
    ExplanationSplit the record into fields
  10. 10
    ExampleConvert and calculate
  11. 11
    Key InsightSeparators can describe patterns
  12. 12
    ChallengeParse after checking shape
  13. 13
    ChallengeNormalize words and join them
  14. 14
    RecapCheck the result type at each stage
5

Compare commands and assemble a report

12 steps
Choose content comparisons, interpret text order, and build an editable result without losing the original.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionCompare meaning and build a result
  2. 2
    ExplanationChoose a content test
  3. 3
    ExampleIgnore case without ignoring spaces
  4. 4
    ChallengeExplain a literal-based test
  5. 5
    ExplanationOrder by the first different char
  6. 6
    ChallengeKeep the earliest text candidate
  7. 7
    ExplanationAppend to one changeable sequence
  8. 8
    ExamplePlace separators between parts
  9. 9
    ExampleEdit the current positions
  10. 10
    ChallengeKeep the original order
  11. 11
    ChallengeBuild a filtered report
  12. 12
    RecapUse the operation that matches the question

Java Arrays and ArrayLists practice questions

40 Practice Questions in 4 sets

Set 1: Create, edit, and share collections10 Practice Questions

Question 1 of 10

What declaration creates an empty, changeable list of integer values? Assume ArrayList and List are imported.
  1. ArrayList<int> n = new ArrayList<>();
  2. Integer[] n = new Integer[0];
  3. ArrayList<Integer> n = new ArrayList<>();
  4. List<Integer> n = List.of();
Show answerHide answer
Answer: C
The wrapper type Integer is the element type for a list of integer values. ArrayList<int> does not compile because a primitive cannot be a generic type argument. A zero-length array and an unmodifiable List.of() also cannot provide the requested growing list.

Question 2 of 10

What does this print?

ArrayList<String> tools = new ArrayList<>(List.of("pen", "ruler"));
tools.add(1, "tape");
String old = tools.set(2, "clip");
System.out.println(old + ": " + tools);
  1. ruler: [pen, tape, clip]
  2. tape: [pen, clip, ruler]
  3. ruler: [pen, clip, tape]
  4. clip: [pen, tape, clip]
Show answerHide answer
Answer: A
Inserting at index 1 shifts "ruler" to index 2, so set(2, "clip") replaces it and returns "ruler". The final list is [pen, tape, clip]. Returning "clip" would confuse the new replacement with the old value that set returns.

Question 3 of 10

An ArrayList<Integer> holds [12, 24, 36]. What call removes the value 24?
  1. values.remove(24);
  2. values.remove(Integer.valueOf(1));
  3. values.set(1, 24);
  4. values.remove(Integer.valueOf(24));
Show answerHide answer
Answer: D
Wrapping 24 with Integer.valueOf selects removal by value, so the list becomes [12, 36]. Passing the primitive int 24 instead selects removal by index and fails because index 24 does not exist. Replacing index 1 with 24 would leave the list unchanged.

Question 4 of 10

A name list holds [Nora, Ravi, Nora, Mei]. After names.remove("Nora"), what are names.indexOf("Nora") and names.lastIndexOf("Mei"), in that order?
  1. 0 and 3
  2. 1 and 2
  3. -1 and 2
  4. 2 and 3
Show answerHide answer
Answer: B
Removal by value deletes only the first "Nora", leaving [Ravi, Nora, Mei]. The remaining Nora is at index 1, and Mei has shifted to index 2. A result of -1 for Nora would assume that one removal deletes every equal value.

Question 5 of 10

What are the contents of a and c after this code?

ArrayList<String> a = new ArrayList<>(List.of("oak"));
ArrayList<String> b = a;
ArrayList<String> c = new ArrayList<>(a);
b.add("elm");
c.set(0, "ash");
  1. a: [oak]; c: [ash]
  2. a: [oak, elm]; c: [ash]
  3. a: [ash, elm]; c: [ash, elm]
  4. a: [oak, elm]; c: [ash, elm]
Show answerHide answer
Answer: B
The assignment to b shares a reference with a, so adding through b changes their one list. The copy constructor creates c before that addition, leaving it with one independent slot. Expecting elm in c would treat a copy as a live link to later additions.

Question 6 of 10

What does Arrays.toString(new boolean[3]) return?
  1. "[null, null, null]"
  2. "[0, 0, 0]"
  3. "[]"
  4. "[false, false, false]"
Show answerHide answer
Answer: D
A new boolean array has three slots, each initialized to false, and Arrays.toString prints all of them. Null is the default for slots holding object references, not primitive booleans. The slots already exist even though no values were assigned explicitly.

Question 7 of 10

A double[] readings has length 6. What expression reads its final slot?
  1. readings[5]
  2. readings[6]
  3. readings.get(5)
  4. readings[readings.length()]
Show answerHide answer
Answer: A
Six array slots use indexes 0 through 5, so the final slot is readings[5]. Index 6 is one position past the end and throws an exception. Array access uses square brackets, and its length is a field without parentheses.

Question 8 of 10

What are the contents of a and b after this code?

int[] a = {7, 3};
int[] b = Arrays.copyOf(a, 3);
b[0] = 8;
  1. a: [8, 3]; b: [8, 3, 0]
  2. a: [7, 3]; b: [8, 3]
  3. a: [7, 3]; b: [8, 3, 0]
  4. a: [7, 3, 0]; b: [8, 3, 0]
Show answerHide answer
Answer: C
The copy is a new three-slot array, with the extra int slot initialized to 0. Changing its first slot leaves the original two-slot array unchanged. Showing 8 in a would confuse copying with the shared reference created by b = a.

Question 9 of 10

Two separately created arrays each contain {6, 2}. What are the results of a.equals(b) and Arrays.equals(a, b), in that order?
  1. false, true
  2. true, true
  3. true, false
  4. false, false
Show answerHide answer
Answer: A
Array equals inherits identity comparison, so the separately created arrays are not equal by that call. Arrays.equals compares corresponding values and returns true. Expecting both calls to return true applies ArrayList content-equality behavior to an array.

Question 10 of 10

What does the caller's list contain after edit(a)?

static void edit(ArrayList<Integer> x) {
    x.set(0, x.get(0) + 2);
    x = new ArrayList<>(x);
    x.add(9);
}
// In main:
ArrayList<Integer> a = new ArrayList<>(List.of(5, 8));
edit(a);
  1. [5, 8]
  2. [7, 8, 9]
  3. [7, 8]
  4. [5, 8, 9]
Show answerHide answer
Answer: C
The initial set edits the shared caller list, changing 5 to 7. The parameter is then redirected to a separate copy, and only that copy receives 9. The caller keeps [7, 8]; including 9 would incorrectly make parameter reassignment redirect the caller variable too.
Set 2: Trace loops and process text10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

After for (int n : values) { n += 3; } on the array {2, 6, 9}, what does the array contain?
  1. [5, 9, 12]
  2. [3, 3, 3]
  3. [9, 9, 9]
  4. [2, 6, 9]
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An integer list holds [5, 8, 9]. After summing it into an int total, what value does (double) (total / values.size()) produce?
  1. 7.333333333333333
  2. 7.0
  3. 22.0
  4. 3.0
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

For the nonempty list [-8, -3, -3, -6], what pair does this code print?

int best = 0;
int total = 0;
for (int i = 0; i < values.size(); i++) {
    int n = values.get(i);
    total += n;
    if (n >= values.get(best)) {
        best = i;
    }
}
System.out.println(best + ": " + (double) total / values.size());
  1. 2: -5.0
  2. 1: -5.0
  3. 2: -3.0
  4. 0: -5.0
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

The method is called with {"Birch", "Cedar", "Maple"} and target "Maple". What does it return?

static int find(String[] a, String target) {
    for (int i = 0; i < a.length; i++) {
        if (a[i].equals(target)) return i;
        else return -1;
    }
    return -1;
}
  1. 0
  2. 2
  3. -1
  4. 3
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What list remains after this loop?

ArrayList<Integer> a = new ArrayList<>(List.of(4, 4, 7, 2));
for (int i = 0; i < a.size(); i++) {
    if (a.get(i) % 2 == 0) a.remove(i);
}
  1. [7]
  2. [4, 7]
  3. [4, 7, 2]
  4. [4, 4, 7]
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What does "Count: " + 2 + 6 produce?
  1. "Count: 26"
  2. "Count: 8"
  3. "8Count: "
  4. "Count: 2 6"
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

For String code = "AB:472:Q";, what is code.substring(code.indexOf(":") + 1, code.lastIndexOf(":"))?
  1. ":472"
  2. "472:"
  3. "47"
  4. "472"
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What is the type returned by "Mina;18;Oslo".split(";")?
  1. ArrayList<String>
  2. String
  3. String[]
  4. int[]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

How many fields does this expression produce?

"x,y,,".split(",")
  1. 3
  2. 4
  3. 2
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What is printed?

String[] p = "  Omar, 12, 5  ".trim().split(",");
int distanceKm = Integer.parseInt(p[1].trim());
int hours = Integer.parseInt(p[2].trim());
double speed = distanceKm / hours;
System.out.println(speed);
  1. 2.4
  2. 12.5
  3. NumberFormatException
  4. 2.0
Show answerHide answer

Save this lesson to see this answer.

Set 3: Compare values and diagnose mistakes10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What expression safely checks whether a possibly null String named reply contains exactly "ready"?
  1. reply.equals("ready")
  2. "ready".equals(reply)
  3. reply == "ready"
  4. reply.compareTo("ready") == 0
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A builder holds "note". After sb.append(3), what text does it hold?
  1. "note"
  2. "3note"
  3. "note 3"
  4. "note3"
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does "18".compareTo("4") < 0 evaluate to, and why?
  1. true; the first character decides the order
  2. false; eighteen is greater than four
  3. true; two-character strings always come first
  4. false; the longer string always comes later
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What text is stored in result?

StringBuilder sb = new StringBuilder("plane");
sb.delete(1, 3);
sb.insert(1, "i");
String result = sb.toString();
  1. "pie"
  2. "pilane"
  3. "pine"
  4. "pline"
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What does this code print?

String label = "lamp";
String other = label;
label = label.toUpperCase();
System.out.println(other + ":" + label);
  1. Both variables keep their original lowercase text.
  2. Both variables refer to the uppercase result.
  3. The original becomes uppercase; the new result stays lowercase.
  4. The original stays lowercase; the reassigned variable is uppercase.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What does this print?

String[] a = {"ax", "beta", "brim", "sun"};
int first = -1;
int matches = 0;
for (int i = 0; i < a.length; i++) {
    if (a[i].startsWith("b")) {
        if (first == -1) first = i;
        matches++;
    }
}
System.out.println(first + ":" + matches);
  1. 1:2
  2. 2:2
  3. 1:1
  4. -1:2
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What list remains after this code?

ArrayList<Integer> a = new ArrayList<>(List.of(2, 5, 2));
for (int i = a.size() - 1; i >= 0; i--) {
    if (a.get(i) == 2) a.remove(i);
}
int n = a.size();
for (int i = 0; i < n; i++) {
    a.add(a.get(i) * 2);
}
  1. [5, 2, 10, 4]
  2. [5]
  3. [5, 10]
  4. [2, 5, 2, 4, 10, 4]
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What are a and b after the code runs?

int[] a = {11, 4, 8};
int[] b = a;
int temp = b[0];
b[0] = b[2];
b[2] = temp;
b = Arrays.copyOf(b, 4);
b[1] = 0;
  1. a: [11, 4, 8]; b: [8, 0, 11, 0]
  2. a: [8, 4, 11]; b: [8, 0, 11, 0]
  3. a: [8, 0, 11]; b: [8, 0, 11, 0]
  4. a: [8, 4, 8]; b: [8, 0, 8, 0]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A list is empty. A program tests names.indexOf("Iris") >= 0 before calling get with that result. What happens?
  1. The test is false, so get is skipped.
  2. The test is true, and get returns null.
  3. indexOf throws because the list is empty.
  4. The test is true, and get throws.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What is printed?

StringBuilder a = new StringBuilder("drawer");
StringBuilder b = a;
String result = b.reverse().toString();
b = new StringBuilder("x");
System.out.println(a + ":" + result);
  1. drawer:reward
  2. x:reward
  3. reward:reward
  4. reward:drawer
Show answerHide answer

Save this lesson to see this answer.

Set 4: Combine collection and text operations10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

The method should return the text after the first "#" or "missing" when there is no marker. What replacement makes the method work for both inputs "tag#blue" and "plain"?

static String tail(String s) {
    int p = s.indexOf("#");
    MISSING
}
  1. if (p == 0) return "missing"; return s.substring(p + 1);
  2. if (p == -1) return "missing"; return s.substring(p);
  3. if (p == -1) return "missing"; return s.substring(p + 1);
  4. if (p > 0) return "missing"; return s.substring(p + 1);
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What String does the method return for the array {"A", "B", "C"}?

static String report(String[] parts) {
    StringBuilder sb = new StringBuilder();
    for (int i = parts.length - 1; i >= 0; i--) {
        if (sb.length() > 0) sb.append("/");
        sb.append(parts[i]);
    }
    sb.deleteCharAt(2);
    return sb.toString();
}
  1. "C/B/A"
  2. "C/BA"
  3. "A//C"
  4. "C//A"
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What are a and b after change(a)?

static void change(ArrayList<String> x) {
    x.remove("red");
    x = new ArrayList<>();
    x.add("gold");
}
// In main:
ArrayList<String> a = new ArrayList<>(List.of("red", "blue", "red"));
ArrayList<String> b = a;
change(a);
  1. a: [gold]; b: [blue, red]
  2. a: [blue, red]; b: [blue, red]
  3. a: [blue]; b: [blue]
  4. a: [red, blue, red]; b: [red, blue, red]
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What are the results of " ".isEmpty() and " ".isBlank(), in that order?
  1. true, true
  2. false, false
  3. false, true
  4. true, false
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What are the pieces from this expression?

"  north   east west ".trim().split("\\s+")
  1. [north, east, west]
  2. [, north, east, west]
  3. [north, , , east, west]
  4. [north east west]
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A nonempty name list holds ["zen", "Able", "apple"]. A loop keeps the first candidate and replaces it when name.compareTo(first) < 0. What name remains?
  1. apple, because case is ignored during comparison
  2. Able, because its first char precedes the lowercase ones
  3. zen, because later candidates never compare before it
  4. No candidate, because mixed-case comparisons throw
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An ArrayList<String> has size 4. What happens when add(4, "new") is followed by get(4)?
  1. The insertion throws; get is never reached.
  2. The insertion succeeds; get throws afterward.
  3. The insertion replaces the old final element.
  4. The insertion succeeds; get returns "new".
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What are the final out list and average?

int[] a = {-2, 6, 10, 0};
ArrayList<Integer> out = new ArrayList<>();
int sum = 0;
for (int n : a) {
    if (n > 0) {
        out.add(n);
        sum += n;
    }
}
double average = (double) sum / out.size();
  1. [6, 10] and 4.0
  2. [6, 10] and 8.0
  3. [-2, 6, 10, 0] and 3.5
  4. [6, 10, 0] and 5.333333333333333
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What index is returned for the shown input?

static int firstLong(String[] words, int min) {
    for (int i = 0; i < words.length; i++) {
        String clean = words[i].trim();
        if (clean.length() >= min) return i;
    }
    return -1;
}
// Call:
firstLong(new String[] {"  ox  ", "pine", " map ", "cedar"}, 4)
  1. 0
  2. 3
  3. -1
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What are a and kept after this code?

ArrayList<Integer> a = new ArrayList<>(List.of(2, -1, -1, 5));
ArrayList<Integer> kept = new ArrayList<>(a);
for (int i = kept.size() - 1; i >= 0; i--) {
    if (kept.get(i) < 0) kept.remove(i);
}
a.set(0, 9);
  1. a: [9, -1, -1, 5]; kept: [2, 5]
  2. a: [9, 5]; kept: [9, 5]
  3. a: [9, -1, -1, 5]; kept: [9, 5]
  4. a: [9, -1, -1, 5]; kept: [2, -1, 5]
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

66 Key Terms, each with its definition

A

Accumulator
An accumulator stores a result built across loop passes, beginning before the loop and changing as relevant elements are processed.
A sum accumulator starts at 0 and adds each distance so the program can report total kilometers.
Alias
An alias is another variable or name referring to the same object, so edits through one name are visible through the other.
After b = a, b is an alias of a; b.clear() empties the list read through both variables.
Append
An append operation adds a value's text representation to the end of a StringBuilder and returns that same builder for further calls.
An append of 4 after "Page " changes the builder to "Page 4" without a separate reassignment.
Array
An array is an object with a fixed number of same-type slots, accessed by zero-based indexes through square brackets.
An array of seven doubles can store one temperature in degrees Celsius for each day of a week.
Array copy
An array copy is a separate array populated from an existing array, optionally with a different length and default-filled extra slots.
An array copy created with Arrays.copyOf(a, 5) can grow the storage without changing a's length.
Array initializer
An array initializer supplies element values when an array is created, with the value count determining the array's length.
The array initializer in int[] a = {3, 6, 9}; creates three slots containing those values.
ArrayIndexOutOfBoundsException
An ArrayIndexOutOfBoundsException reports an attempt to read or write an array position outside its valid index range.
An ArrayIndexOutOfBoundsException occurs when code reads index 4 of a four-element array.
ArrayList
An ArrayList is an ordered, changeable list whose element count grows or shrinks as values are added or removed.
An ArrayList can collect names as people enter them without requiring a final count in advance.
Autoboxing
Autoboxing is Java's automatic conversion of a primitive value into an object of its corresponding wrapper class.
Autoboxing allows numbers.add(8) even though the list's element type is Integer, not int.

B

Backward removal
Backward removal visits list indexes from last to first, so deletion shifts only elements that the loop has already checked.
Backward removal deletes adjacent negative values without skipping the one that slides left after deletion.

C

Case-sensitive comparison
A case-sensitive comparison treats uppercase and lowercase letters as distinct when deciding whether text matches.
A case-sensitive comparison with String equals finds that "Go" and "go" have different contents.
Char
A char is a primitive Java value storing one UTF-16 code unit, written as a character literal in single quotes.
The char returned by "book".charAt(0) is 'b', while "b" is a String with length 1.
compareTo
The compareTo method reports negative, zero, or positive according to how the receiver orders against its argument.
String compareTo uses UTF-16 char values, so a result below zero means the receiver comes first.
Concatenation
Concatenation joins values into text; in Java, String addition with + proceeds from left to right unless parentheses change grouping.
Concatenation makes "N=" + 2 + 5 produce "N=25", since the numbers are joined after text begins.
ConcurrentModificationException
A ConcurrentModificationException can report that a collection changed in a way its active iterator was not prepared to follow.
A ConcurrentModificationException can occur in one thread when a for-each body removes from its source list.
Conditional count
A conditional count records how many elements pass a test by adding one to a counter only when the test succeeds.
A conditional count can record how many daily temperatures exceed 30 degrees Celsius.
Content comparison
A content comparison tests characters or values stored in objects, allowing separate String objects to match when their text is equal.
A content comparison with reply.equals("go") recognizes matching text even when the objects differ.
Content equality
Content equality checks whether containers have corresponding equal elements in order, instead of requiring one shared object.
For int arrays, content equality is tested with Arrays.equals(a, b), not the array's equals.

D

Default value
A default value is the initial value Java assigns to a newly created array slot, such as zero, false, or null for its type.
The default value in each slot of a new String array is null, so no String methods can run there yet.

E

Early return
An early return ends a method as soon as its result is known, such as when a first-match search reaches a matching element.
An early return from inside the matching if avoids checking names after the first successful match.
Exclusive end
An exclusive end marks the first position left out of a range, making the number of included positions equal to end minus start.
The exclusive end 5 in substring(2, 5) includes positions 2, 3, and 4 but leaves out position 5.

F

Field
A field is one data part in a record, often separated from neighboring parts by a delimiter such as a comma or semicolon.
The second field of "Ari,18,4" must be parsed if a program needs its numeric value for a calculation.
Filter
A filter selects elements passing a condition and can collect them in a new list while leaving the original collection unchanged.
A filter keeps words of length at least five by adding matching words to a separate result list.
For-each loop
A for-each loop visits each element value in order without an explicit index, placing that value in a local loop variable.
A for-each loop can total array values, but reassigning its int variable does not replace the array slots.

I

Identity comparison
An identity comparison checks whether references identify the same object, regardless of whether separate objects hold equal data.
An identity comparison with a == b is false for separate arrays containing the same integers.
Immutability
Immutability means an object's stored state cannot change after creation, so String transformations return results without editing it.
String immutability leaves an old alias unchanged when another variable keeps the result of toUpperCase().
In-place edit
An in-place edit changes an existing object's state, so references already pointing to that object observe the changed contents.
An in-place edit with reverse() changes the original builder, so aliases see the reversed text too.
Index
An index is a zero-based position identifying an element in a list, array, or string; the first position is 0.
The index of the final element in a four-element list is 3, so get(3) reads that element.
Index loop
An index loop visits elements through an explicit position variable, allowing the body to read positions or replace stored values.
An index loop can print names with line numbers by reading names.get(i) and displaying i + 1.
Integer division
Integer division divides integer operands and drops the fractional part, even when the resulting quotient is later stored as a double.
Integer division makes 17 / 4 equal 4; casting an operand first allows the fractional result 4.25.
Iterator
An iterator tracks traversal through a collection, providing the next value and supporting removal through its own method.
An Iterator can remove the just-read even number with it.remove() while continuing through the list.

J

Join
A join operation combines text parts into one String with a chosen separator placed between the parts instead of after the last one.
A join with String.join("/", pieces) turns the parts "a", "b", and "c" into the text "a/b/c".

L

Length field
The length field reports the fixed number of slots in an array and is read without the parentheses used for a method call.
The length field in new int[4] is 4 even before the program writes any custom values to its slots.
Lexicographic order
Lexicographic order compares sequences at their first differing position, placing a shorter equal-prefix string before a longer one.
Java lexicographic order places "12" before "8" because the first differing char is '1' versus '8'.
Linear search
A linear search checks elements one by one until a match answers the question or the end establishes that no element matches.
A linear search for a missing name in 14 entries checks all 14 before returning its failure marker.
Literal replacement
A literal replacement substitutes exact matching text or characters without interpreting the target as a regular-expression pattern.
A literal replacement with replace(".", "-") changes the dots in "a.b.c" into hyphens.
Loop bound
A loop bound is a limit in a loop's condition that determines which positions or iterations the body may process.
A loop bound of i < a.length - 1 leaves room for reading the right neighbor at a[i + 1].

M

Maximum
A maximum is the greatest value in a nonempty data set; a loop can keep a best-so-far value or the index where it appears.
The maximum of {-7, -2, -5} is -2, which a zero-initialized best value would fail to report.
Method chaining
Method chaining calls another method directly on a result returned by a preceding call, as when append returns the same builder.
Method chaining supports sb.append("x").append(2), but cannot continue from void-returning setCharAt.
Method overload
A method overload is one of several methods with the same name but different parameter types or parameter counts.
The removal method overload selected by an int argument treats that argument as an index.

N

NaN
NaN means “not a number” and is a floating-point result for operations such as dividing a zero total by a zero count.
An empty-data average calculated as 0.0 / 0 produces NaN instead of a useful measurement.
Null
Null is the reference value that identifies no object, so an instance method cannot be called through that reference.
A null result must be checked before code calls length() on a String that a search might return.
NumberFormatException
A NumberFormatException reports that text cannot be converted to the numeric type using the requested parsing method.
A NumberFormatException results from Integer.parseInt(" 18") because the leading space is not accepted.

P

Palindrome
A palindrome reads the same forward and backward under the chosen comparison rule, such as ignoring case and nonletter characters.
A palindrome check can normalize letters, reverse a new builder, and compare the resulting Strings.
Parsing
Parsing converts text into a structured value, such as an int or double, according to the syntax accepted by the chosen method.
Parsing "3.5" with Integer.parseInt fails because that method accepts integer text without a decimal point.
Pass by value
Pass by value means a method parameter receives a copy of an argument's value, including a copied reference for an object.
Pass by value lets a list parameter edit shared elements but keeps parameter reassignment local.

R

Reference
A reference is a value that identifies an object, allowing a variable to reach that object instead of holding its contents directly.
A copied reference lets two variables add elements to the same ArrayList object in memory.
Regular expression
A regular expression is a text pattern whose symbols can describe matches beyond exact literal characters, as in String split separators.
A regular expression containing an unescaped dot matches characters instead of splitting only at literal dots.
Removal by index
Removal by index deletes the element at a given position, returns that element, and shifts every later element left.
Removal by index changes [a, b, c] to [a, c] when remove(1) deletes the middle element.
Removal by value
Removal by value deletes the first equal element and returns whether a matching element was actually removed.
Removal by value leaves one duplicate in [a, b, a] after remove("a") removes the first a.

S

Search predicate
A search predicate is a true-or-false test that decides whether an element matches a search condition such as a required prefix.
The search predicate city.startsWith("M") finds names by a condition instead of one exact value.
Search result
A search result reports whether or where matching data was found; list index searches use -1 to report no match.
The search result from names.indexOf("Kai") can be 0, so a found test must accept that index.
Sentinel value
A sentinel value is a specially chosen result marking a condition such as no match, distinct from ordinary successful results.
The sentinel value -1 signals that an index search failed because no valid index can be negative.
Shallow copy
A shallow copy creates a separate container while copying its element values or references without duplicating referenced objects.
A shallow copy of a string list has independent list slots that still refer to the same String objects.
Split
A split operation divides text at separator-pattern matches and returns an array of text pieces without the separators themselves.
A split at commas turns "Nia,25,Lima" into three strings, including the still-unparsed number text.
String
A String is an immutable Java object representing text as a sequence of UTF-16 char values accessed through zero-based positions.
A String containing a name can be shared safely because converting its case does not edit the original object.
StringBuilder
A StringBuilder is a changeable character sequence that supports efficient repeated appending and edits to current positions or ranges.
A StringBuilder can assemble a multi-line report without rebuilding the whole prefix after every added line.
Structural modification
A structural modification changes an ArrayList's size or underlying structure, such as adding or removing an element during traversal.
A structural modification through the source list can invalidate the state of its for-each iterator.
Substring
A substring is a contiguous part of a String, selected by a beginning index and optionally an end index that is excluded.
The substring from indexes 1 through 3 of "planet" is selected with substring(1, 4) and reads "lan".

T

Temporary variable
A temporary variable holds an intermediate value while other assignments change the positions from which that value was read.
A temporary variable saves the first element during a swap so the next assignment does not lose it.
Traversal
A traversal is a systematic visit to collection elements, such as moving from the first element to the last with a loop.
A backward traversal starts at the last index and reaches index 0 before the loop finishes.

U

Unboxing
Unboxing is Java's automatic conversion of a wrapper object's stored value into the corresponding primitive type.
Unboxing supplies an int when int first = numbers.get(0); reads an Integer list element.
Unmodifiable list
An unmodifiable list rejects changes to its elements and structure, including addition, removal, and replacement.
The unmodifiable list returned by List.of("east", "west") rejects a later call to set.
UTF-16 code unit
A UTF-16 code unit is the unit stored by a Java char; a displayed symbol can need one unit or a pair of them.
An emoji can occupy two UTF-16 code units, affecting the count returned by String length().

W

Whitespace
Whitespace consists of spacing or separating characters recognized by a particular test, including spaces, tabs, and line breaks.
Java whitespace is recognized by Character.isWhitespace, which is also used by strip() and isBlank().
Wrapper class
A wrapper class represents a primitive value as an object, allowing values such as integers to be used as list elements.
The wrapper class Integer lets an ArrayList<Integer> store numbers supplied as int values.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started