Codecademy will be down from 00:00 to 02:00 ET on November 15, 2019 for scheduled database maintenance. This will affect the website, learning environment, forums, and mobile app. We will provide updates as necessary.
Cheat Sheets are in BETA. Give us your feedback.

Java arrays

In Java, an array is used to store a list of elements of the same datatype.

Arrays are a fixed size, their elements are ordered, and the elements can be accessed using an index, which starts with 0.

// create an array of 5 int elements int[] marks = {10, 20, 30, 40, 50}; // print out the first element of the marks array at index = 0 System.out.println(marks[0]);

Array creation in Java

In Java, an array can be created in the following ways:

  • Using the {} notation, by adding each element all at once.
  • Using the new keyword, and assigning each position of the array individually.
int[] age = {20, 21, 30}; int[] marks = new int[3]; marks[0] = 50; marks[1] = 70; marks[2] = 93;

Accessing elements in a Java array

In Java, we can use an index to access the associated element in an array.

The index of an array starts from 0 and goes up to one less than the total length of the array.

// Here, we create an array of 5 elements int[] marks = {50, 55, 60, 70, 80}; // print the first element at index 0 System.out.println(marks[0]); // Output: 50 // print the last element at index 4 (80) System.out.println(marks[4]); // Output: 80