- Learn
- Computer Science & IT
- Programming
- Object-Oriented Programming with Java
- Java Arrays and ArrayLists
Java Arrays and ArrayLists: Lists, Loops and Strings
BeginnerLesson 4 of 11 in Object-Oriented Programming with Java Course
What you will learn
- 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 indexImport 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 containsRemove 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 methodsExplain 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.
- Create a list and work with elements by index
- 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 elementsDeclare 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 listsExplain array references, copy and compare arrays correctly, swap elements, and decide when an array or an ArrayList fits the task.
- Create arrays and access their elements
- 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-eachWrite 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 extremesUse accumulator variables to compute sums, averages, counts, maximums and minimums, and build a filtered list.
- Search a list or array for a valueWrite 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 itRemove or add elements during a loop without skipping elements or causing an exception, and choose a safe way to do it.
- Loop through lists and arrays with for and for-each
- 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 stringUse 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 stringLocate 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 numbersBreak a line into fields with split, convert fields to numbers and numbers to text, check the parts, and join parts back together.
- Read the characters of a string
- Compare strings by content and by alphabetical order, and use StringBuilder to build and edit text step by step.
- Compare strings with equals and compareToUse 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 StringBuilderUse StringBuilder to build text in a loop and edit it in place, convert the result to a String, and avoid the common StringBuilder mistakes.
- Compare strings with equals and compareTo
Java Arrays and ArrayLists study guide
1Store 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.
| Task | Call | Valid index |
|---|---|---|
| Read an element | get(i) | 0 through size() - 1 |
| Replace an element | set(i, value) | 0 through size() - 1 |
| Insert an element | add(i, value) | 0 through size() |
| Append an element | add(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. setreplaces; indexedaddinserts and shifts later elements.- Use wrapper types such as
Integerin 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
| Call | Meaning | Result returned |
|---|---|---|
remove(int index) | Remove the element at a position | The removed element |
remove(Object value) | Remove the first equal value | true 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.
indexOfandlastIndexOfreturn -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
equalscompares ordered contents;==compares identity. - An empty list supports iteration;
nullrefers to no list.
2Store 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.
| Structure | Number of elements | Read an element |
|---|---|---|
| Array | a.length | a[i] |
| ArrayList | a.size() | a.get(i) |
| String | s.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 anda.lengthto 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
| Need | Suitable choice |
|---|---|
| A fixed slot for each day or month | Array |
| Primitive values without wrappers | Array |
| Add or remove elements as input arrives | ArrayList |
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;
copyOforclonecreates a copy. - Use
Arrays.equalsfor 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.
3Process 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 + 1needsi < 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
removeduring 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.
4Work 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
| Expression | Result |
|---|---|
"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 atlength() - 1.- Chars use single quotes; strings use double quotes.
- String length counts UTF-16 char values, so some symbols occupy two positions.
Charactermethods 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
| Method | Effect |
|---|---|
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.
replacereplaces literal text;trimandstripact at the ends.isBlankaccepts whitespace-only text, whileisEmptyneeds 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
splitreturns 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.joinfor text parts and parsing methods for numbers.
5Compare 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.
| Comparison | Sign | Reason |
|---|---|---|
"apple".compareTo("banana") | Negative | First differing char is earlier |
"pear".compareTo("pear") | Zero | All characters match |
"car".compareTo("carpet") | Negative | Equal 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
equalsfor String contents andequalsIgnoreCaseto ignore case. - A known literal can safely receive
equalswhen 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
| Method | Effect |
|---|---|
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
appendto build a long result andtoStringto finish it. - Put separators between values, avoiding an extra final separator.
- Builder edits change the existing builder; range ends are excluded.
setCharAtreturns void, so it cannot be chained.reversechanges the builder you call it on.- Convert builders to Strings before comparing contents.
Java Arrays and ArrayLists examples
1Build and share a reading list
13 steps
- 1IntroductionTrack 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.
- 2ExplanationCreate 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. - 3ExampleInsert 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 intoold. The final list is[Orbit, Cloud, Forest]. Unlike insertion, replacement has not changed the size. - 4ChallengeFind the next valid position
The list is
[Orbit, Cloud, Forest]. What happens if you callreading.add(3, "Dune")? What wouldreading.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. - 5ExplanationRemove 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]andremovedis true. Forest and every later element move one position left. The final Cloud remains in the list. - 6TipAsk whether or where
For
[Orbit, Forest, Dune, Cloud],contains("Orbit")is true andindexOf("Orbit")is 0. A found test must accept index 0: useindex != -1after saving the search result. A missing title returns -1. Searches compare String contents with case sensitivity, so searching for"orbit"does not find"Orbit". UselastIndexOfwhen the last matching position matters. - 7ChallengeRemove 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. - 8AnalogyTwo 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, soshared.add("Coast")is visible throughreading. A copy constructor,new ArrayList<>(reading), instead creates another list with its own slots. - 9ExampleCopy 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. - 10Key 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. Assigningtitles = 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. Callingsize()on empty returns 0, while calling it through null fails. - 11ChallengeSeparate 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. - 12ChallengeCombine a copy, search, and edit
Let a hold
[Lake, Hill], then runb = new ArrayList<>(a),b.add("Lake"), andb.remove(b.indexOf("Lake")). What do a and b contain, and doesa.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 listequalsreturns false. - 13RecapPredict a list change
Read an edit by identifying its target first: a position for
setor indexed removal, a value for value removal, and an insertion position foradd. 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.
2Store and copy fixed readings
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each reading a fixed slot
- 2ExplanationAllocate the slots
- 3ExamplePrint the data you need
- 4ChallengeRead the final slot
- 5ExampleFollow an alias
- 6ExampleCreate a larger copy
- 7ChallengeChoose a content comparison
- 8ExampleSave before overwriting
- 9ChallengeKeep old data while expanding
- 10RecapSeparate slot edits from new storage
3Turn readings into results
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionGive each loop one clear job
- 2ExplanationRead values or read positions
- 3ChallengeLeave room for a neighbor
- 4ExampleCarry a sum across the loop
- 5ExampleDivide after keeping the fraction
- 6Key InsightAn extreme needs a real candidate
- 7ChallengeTrack the last tied maximum
- 8ExplanationStop only when the answer is known
- 9ExampleFind the first reading above a limit
- 10ChallengeChange from first match to all matches
- 11ExampleWatch a forward deletion skip
- 12ExplanationWalk backward for removal
- 13ConnectionKeep the source by filtering
- 14TipUse the iterator that owns the traversal
- 15ChallengeBound a loop that appends
- 16ChallengeAverage only the selected values
- 17RecapTrace state and stopping rules
4Read a text record in stages
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFrom raw text to data
- 2ExplanationRead one character at a time
- 3ExampleCount digits in a label
- 4ChallengeKeep a transformation
- 5ExplanationLocate a boundary first
- 6ExampleCount the included positions
- 7TipChoose the cleanup rule
- 8ChallengeHandle a missing separator
- 9ExplanationSplit the record into fields
- 10ExampleConvert and calculate
- 11Key InsightSeparators can describe patterns
- 12ChallengeParse after checking shape
- 13ChallengeNormalize words and join them
- 14RecapCheck the result type at each stage
5Compare commands and assemble a report
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionCompare meaning and build a result
- 2ExplanationChoose a content test
- 3ExampleIgnore case without ignoring spaces
- 4ChallengeExplain a literal-based test
- 5ExplanationOrder by the first different char
- 6ChallengeKeep the earliest text candidate
- 7ExplanationAppend to one changeable sequence
- 8ExamplePlace separators between parts
- 9ExampleEdit the current positions
- 10ChallengeKeep the original order
- 11ChallengeBuild a filtered report
- 12RecapUse the operation that matches the question
Java Arrays and ArrayLists practice questions
Set 1: Create, edit, and share collections10 Practice Questions
Question 1 of 10
Show answerHide answer
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);
Show answerHide answer
"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
ArrayList<Integer> holds [12, 24, 36]. What call removes the value 24?Show answerHide answer
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
[Nora, Ravi, Nora, Mei]. After names.remove("Nora"), what are names.indexOf("Nora") and names.lastIndexOf("Mei"), in that order?Show answerHide answer
"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");
Show answerHide answer
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
Arrays.toString(new boolean[3]) return?Show answerHide answer
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
double[] readings has length 6. What expression reads its final slot?Show answerHide answer
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;
Show answerHide answer
a would confuse copying with the shared reference created by b = a.Question 9 of 10
{6, 2}. What are the results of a.equals(b) and Arrays.equals(a, b), in that order?Show answerHide answer
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);
Show answerHide answer
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
for (int n : values) { n += 3; } on the array {2, 6, 9}, what does the array contain?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
[5, 8, 9]. After summing it into an int total, what value does (double) (total / values.size()) produce?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());
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;
}
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);
}
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
"Count: " + 2 + 6 produce?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
String code = "AB:472:Q";, what is code.substring(code.indexOf(":") + 1, code.lastIndexOf(":"))?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
"Mina;18;Oslo".split(";")?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
How many fields does this expression produce?
"x,y,,".split(",")
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);
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
reply contains exactly "ready"?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
sb.append(3), what text does it hold?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"18".compareTo("4") < 0 evaluate to, and why?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();
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);
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);
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);
}
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;
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
names.indexOf("Iris") >= 0 before calling get with that result. What happens?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);
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
}
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();
}
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);
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
" ".isEmpty() and " ".isBlank(), in that order?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+")
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
["zen", "Able", "apple"]. A loop keeps the first candidate and replaces it when name.compareTo(first) < 0. What name remains?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
ArrayList<String> has size 4. What happens when add(4, "new") is followed by get(4)?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();
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)
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);
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accumulator
Alias
b = a, b is an alias of a; b.clear() empties the list read through both variables.Append
Array
Array copy
Arrays.copyOf(a, 5) can grow the storage without changing a's length.Array initializer
int[] a = {3, 6, 9}; creates three slots containing those values.ArrayIndexOutOfBoundsException
ArrayList
Autoboxing
numbers.add(8) even though the list's element type is Integer, not int.B
Backward removal
C
Case-sensitive comparison
equals finds that "Go" and "go" have different contents.Char
"book".charAt(0) is 'b', while "b" is a String with length 1.compareTo
Concatenation
+ proceeds from left to right unless parentheses change grouping."N=" + 2 + 5 produce "N=25", since the numbers are joined after text begins.ConcurrentModificationException
Conditional count
Content comparison
reply.equals("go") recognizes matching text even when the objects differ.Content equality
Arrays.equals(a, b), not the array's equals.D
Default value
E
Early return
Exclusive end
substring(2, 5) includes positions 2, 3, and 4 but leaves out position 5.F
Field
Filter
For-each loop
I
Identity comparison
a == b is false for separate arrays containing the same integers.Immutability
toUpperCase().In-place edit
reverse() changes the original builder, so aliases see the reversed text too.Index
get(3) reads that element.Index loop
names.get(i) and displaying i + 1.Integer division
17 / 4 equal 4; casting an operand first allows the fractional result 4.25.Iterator
it.remove() while continuing through the list.J
Join
String.join("/", pieces) turns the parts "a", "b", and "c" into the text "a/b/c".L
Length field
new int[4] is 4 even before the program writes any custom values to its slots.Lexicographic order
Linear search
Literal replacement
replace(".", "-") changes the dots in "a.b.c" into hyphens.Loop bound
i < a.length - 1 leaves room for reading the right neighbor at a[i + 1].M
Maximum
{-7, -2, -5} is -2, which a zero-initialized best value would fail to report.Method chaining
sb.append("x").append(2), but cannot continue from void-returning setCharAt.Method overload
N
NaN
0.0 / 0 produces NaN instead of a useful measurement.Null
length() on a String that a search might return.NumberFormatException
Integer.parseInt(" 18") because the leading space is not accepted.P
Palindrome
Parsing
Integer.parseInt fails because that method accepts integer text without a decimal point.Pass by value
R
Reference
Regular expression
Removal by index
[a, b, c] to [a, c] when remove(1) deletes the middle element.Removal by value
[a, b, a] after remove("a") removes the first a.S
Search predicate
city.startsWith("M") finds names by a condition instead of one exact value.Search result
names.indexOf("Kai") can be 0, so a found test must accept that index.Sentinel value
Shallow copy
Split
String
StringBuilder
Structural modification
Substring
"planet" is selected with substring(1, 4) and reads "lan".T
Temporary variable
Traversal
U
Unboxing
int first = numbers.get(0); reads an Integer list element.Unmodifiable list
List.of("east", "west") rejects a later call to set.UTF-16 code unit
length().W
Whitespace
Character.isWhitespace, which is also used by strip() and isBlank().Wrapper class
Integer lets an ArrayList<Integer> store numbers supplied as int values.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.