1/30/25, 7:14 PM Learn Java: Arrays and ArrayLists Cheatsheet | Codecademy
Cheatsheets / Learn Java
Arrays and ArrayLists
Java ArrayList
In Java, an ArrayList is used to represent a dynamic // import the ArrayList package
list.
import java.util.ArrayList;
While Java arrays are fixed in size (the size cannot be
modified), an ArrayList allows flexibility by being able
to both add and remove elements. // create an ArrayList called students
ArrayList<String> students = new
ArrayList<String>();
Index
An index refers to an element’s position within an array. int[] marks = {50, 55, 60, 70, 80};
The index of an array starts from 0 and goes up to one
less than the total length of the array.
System.out.println(marks[0]);
// Output: 50
System.out.println(marks[4]);
// Output: 80
Arrays
In Java, an array is used to store a list of elements of // Create an array of 5 int elements
the same datatype.
int[] marks = {10, 20, 30, 40, 50};
Arrays are fixed in size and their elements are ordered.
https://www.codecademy.com/learn/learn-java/modules/learn-java-arrays-and-arraylists/cheatsheet 1/3
1/30/25, 7:14 PM Learn Java: Arrays and ArrayLists Cheatsheet | Codecademy
Array creation in Java
In Java, an array can be created in the following ways: int[] age = {20, 21, 30};
Using the {} notation, by adding each element
all at once.
Using the new keyword, and assigning each int[] marks = new int[3];
position of the array individually. marks[0] = 50;
marks[1] = 70;
marks[2] = 93;
Changing an Element Value
To change an element value, select the element via its int[] nums = {1, 2, 0, 4};
index and use the assignment operator to set a new
// Change value at index 2
value.
nums[2] = 3;
https://www.codecademy.com/learn/learn-java/modules/learn-java-arrays-and-arraylists/cheatsheet 2/3
1/30/25, 7:14 PM Learn Java: Arrays and ArrayLists Cheatsheet | Codecademy
Modifying ArrayLists in Java
An ArrayList can easily be modified using built in import java.util.ArrayList;
methods.
To add elements to an ArrayList , you use the add()
method. The element that you want to add goes inside public class Students {
of the () . public static void main(String[] args)
To remove elements from an ArrayList , you use the
{
remove() method. Inside the () you can specify the
index of the element that you want to remove.
Alternatively, you can specify directly the element that // create an ArrayList called
you want to remove. studentList, which initially holds []
ArrayList<String>
studentList = new ArrayList<String>();
// add students to the ArrayList
studentList.add("John");
studentList.add("Lily");
studentList.add("Samantha");
studentList.add("Tony");
// remove John from the ArrayList,
then Lily
studentList.remove(0);
studentList.remove("Lily");
// studentList now holds [Samantha,
Tony]
System.out.println(studentList);
}
}
Print Share
https://www.codecademy.com/learn/learn-java/modules/learn-java-arrays-and-arraylists/cheatsheet 3/3