The Java Parrot — Adding and visiting parrots in an Array and ArrayList with for and while loops

ShipItParrot
6 min readDec 24, 2022

--

Ahoy parrot!

Lets continue from where we left off in the previous article!

The Java Parrot — Working with many things, with Array, and ArrayList

We explored our first data structures; the fixed sized Array, and the dynamic sized ArrayList.

Now, lets parrot on, and share how we can add and go through all items in Array and ArrayList with two new control statements:

  • for
  • while

Add a Parrot to an Array with for-loops

Let’s create a list of parrots!

We’ll start with an empty list and use a for-loop to add some parrots to it.

The for loop has three parts to it, separated by a semi-colon ;

  • The first part defines a variable which will be used in the loop
int i = 0
  • The second part defines the condition for continuing the loop. The loop will continue as long as i is less than 5
i < 5
  • The last part defines the logic to be executed at the end of each for-loop. This increases i by 1, after every iteration.
i++

These three parts have the overall effect of havin the for-loop iterating 5 times.

At the first iteration, iteration 1, i will be set to 0

At iteration 2, i will be set to 1

At iteration 3, i will be set to 2

At iteration 4, i will be set to 3

At the final iteration, iteration 5, i will be set to 4

At each iteration, we are also setting an element at an index to a “Parrot i” String, with the [] operator on the Array!

arr[i] = "Parrot " + i;

And putting it all together, we get this!

import java.util.Arrays;

class ArrayPractice {
public static void main(String[] args) {
// Create an array of String with size 10
String[] arr = new String[5];

// Initialize the first five elements of the array
for (int i = 0; i < arr.length; i++) {
arr[i] = "Parrot " + i;
}

String allParrots = Arrays.toString(arr);

// Output: ["Parrot 0", "Parrot 1", "Parrot 2", "Parrot 3", "Parrot 4"]
System.out.println(allParrots);
}
}

Add a Parrot to an ArrayList with for-loops

Now, lets do the same with a for-loop, but for ArrayList!

The logic of the for-loop is the same; we have the same three parts to the for-loop, and iterate the loop 5 times!

Here is the main difference between adding a Parrot to the Array and the ArrayList!

At each iteration, we are adding the “Parrot i” String to the ArrayList differently, with the .add method on the ArrayList.

import java.util.Arrays;
import java.util.ArrayList;

class ArrayListPractice {
public static void main(String[] args) {
// Create an array of String with size 10
ArrayList<String> arr = new ArrayList<String>();

// Add elements to the ArrayList
for (int i = 0; i < arr.size(); i++) {
arr.add("Parrot " + i);
}

String allParrots = arr.toString();

// Output: ["Parrot 0", "Parrot 1", "Parrot 2", "Parrot 3", "Parrot 4"]
System.out.println(allParrots);
}
}

If we had tried to do the same, but with the [] operator, we would get an error! That operator is not supported for ArrayList.

arr[i] = "Parrot " + i;
➜  arraysAndArrayLists git:(main) ✗ java ArrayListPractice.java
ArrayListPractice.java:11: error: array required, but ArrayList<String> found
arr[i] = "Parrot " + i;

You smart parrots would ask:

“Hey Parrot! What if we wanted to edit an item at a specific index of the ArrayList? There must be a way right?”

And yes you are right! We can use the .set() method on the ArrayList!

Be careful to only call .set on an ArrayList with that index, or we will get an OutOfBoundsException!

import java.util.Arrays;
import java.util.ArrayList;

class ArrayListPractice {
public static void main(String[] args) {
// We have an ArrayList of size 0
ArrayList<String> arr = new ArrayList<String>();

// Add elements to the ArrayList
for (int i = 0; i < arr.size(); i++) {
// This will cause an OutOfBoundsException!
// We are getting index 0 from an ArrayList with no index 0!
arr.set(i, "Parrot " + i);
}

String allParrots = arr.toString();

System.out.println(allParrots);
}
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0

To fix that, we can initialize an ArrayList of size 5.

import java.util.Arrays;
import java.util.ArrayList;

class ArrayListPractice {
public static void main(String[] args) {
// Initialize ArrayList of size 5
ArrayList<String> arr = new ArrayList(Arrays.asList(new String[5]));

// Add elements to the ArrayList
for (int i = 0; i < arr.size(); i++) {
// No errors!
arr.set(i, "Parrot " + i);
}

String allParrots = arr.toString();

// Output: ["Parrot 0", "Parrot 1", "Parrot 2", "Parrot 3", "Parrot 4"]
System.out.println(allParrots);
}
}

Visit each parrot in the Array with for-loops

Here’s an example of how to iterate over an Array using a for-loop!

You smart parrots would notice that it is very similar to how we would add a parrot to an Array!

The only difference, is that we are getting a parrot by index with Array’s [] operator.

import java.util.Arrays;

class ArrayPractice {
public static void main(String[] args) {
// Create an array of String with size 10
String[] arr = new String[5];

// Initialize the first five elements of the array
for (int i = 0; i < arr.length; i++) {
arr[i] = "Parrot " + i;
}

// use a for loop to iterate, by index
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
➜  arraysAndArrayLists git:(main) ✗ java ArrayPractice.java
Parrot 0
Parrot 1
Parrot 2
Parrot 3
Parrot 4

Visit each parrot in the ArrayList with for-loops

Here’s an example of how to iterate over an ArrayList using a for-loop!

Also, it is very similar to how we would add a parrot to an ArrayList!

The only difference, is that we are using ArrayList’s .get() method to get a parrot by index.

import java.util.Arrays;
import java.util.ArrayList;

class ArrayListPractice {
public static void main(String[] args) {
// ArrayList<String> arr = new ArrayList<String>();
// Create an array of String with size 5
ArrayList<String> arr = new ArrayList<String>(Arrays.asList(new String[5]));

// Add elements to the ArrayList
for (int i = 0; i < arr.size(); i++) {
arr.set(i, "Parrot " + i);
}

// use a for loop to iterate, by index
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
}
}
➜  arraysAndArrayLists git:(main) ✗ java ArrayListPractice.java
Parrot 0
Parrot 1
Parrot 2
Parrot 3
Parrot 4

Visit each parrot in the Array with while loops

And here’s an example of how to iterate over an Array using a while-loop:

Let’s use a while-loop to traverse the Array of parrots and perform some action on each one!

For example, we might want to greet each parrot by saying “Hello, [parrot’s name]!”

import java.util.Arrays;

class ArrayPractice {
public static void main(String[] args) {
// Create an array of String with size 10
String[] arr = new String[5];

// Initialize the first five elements of the array
for (int i = 0; i < arr.length; i++) {
arr[i] = "Parrot " + i;
}

int i = 0;

// Use a while loop to iterate
while (i < arr.length) {
System.out.println(arr[i]);
i++;
}
}
}
➜  arraysAndArrayLists git:(main) ✗ java ArrayPractice.java
Parrot 0
Parrot 1
Parrot 2
Parrot 3
Parrot 4

This will output a greeting for each parrot in the Array.

Visit each parrot in the ArrayList with while loops

It is pretty similar to the example with Array! Just two differences!

  • We use ArrayList’s .size() method to get the length instead.
  • We use ArrayList’s .get() method to get a parrot at an index.
import java.util.Arrays;
import java.util.ArrayList;

class ArrayListPractice {
public static void main(String[] args) {
// Create an array of String with size 5
ArrayList<String> arr = new ArrayList<String>(Arrays.asList(new String[5]));

// Add elements to the ArrayList
for (int i = 0; i < arr.size(); i++) {
arr.set(i, "Parrot " + i);
}

int i = 0;

// Use a while loop to iterate
while (i < arr.size()) {
System.out.println(arr.get(i));
i++;
}
}
}
➜  arraysAndArrayLists git:(main) ✗ java ArrayListPractice.java
Parrot 0
Parrot 1
Parrot 2
Parrot 3
Parrot 4

While loops can result in infinite loops if we don’t place a valid terminating condition!

It can be easy to accidentally create an infinite loop with while loops if we do not set up the condition correctly.

For example, if we forgot to increment the value of i inside the while-loop, it would become stuck in an infinite loop.

// Use a while loop to iterate
while (i < arr.length) {
System.out.println(arr[i]);
// i++; // Oops, forgot to increment i!
}

To avoid this, please be an earnest parrot and double-check your while-loop conditions and make sure they will eventually evaluate to False so that the loop can terminate!

Practice is crucial! Be a PracticeItParrot

Here are some recommended LeetCode questions for practice!

  1. 2011. Final Value of Variable After Performing Operations

2. 2114. Maximum Number of Words Found in Sentences

3. 2114. Maximum Number of Words Found in Sentences

You can find our code samples above here!

And thats all parrots! See you in the next one!

--

--