Introduction to Arrays in Java

Hello, welcome to our journey into the world of arrays in Java! Arrays are similar to lists of items, like a roster of superhero names. In this lesson, we will explore how to create arrays, access their elements, and work with their properties. So, let's get started!

Understanding Arrays in Java

An array is a container that stores a fixed number of values of a single type. Think of it as a box that holds only tennis balls or apples. Each item in an array is an element, and their positions are called indices. Let's put this into practice:

int[] numbers = {10, 20, 30, 40, 50}; // creates an array "numbers" of 5 integers

Consider numbers as a box with 5 compartments, each holding a number. Simple, isn't it?

Creation of Arrays in Java

To create an array, we declare it using a type and square brackets, followed by an array name. Then, we use the new keyword to initialize it, specifying the array's length. The process looks like this:

int[] a;                  // Declare an array
a = new int[5];           // Initialize the array with 5 elements
a = new int[]{1, 2, 3, 4, 5};    // Assign values 1, 2, 3, 4, 5 to the array

In this example, we've created an array a that can hold 5 numbers.

However, as you might have noticed already, shorter forms are also available, especially when all array elements are predefined:

int[] a = new int[]{1, 2, 3, 4, 5}; // Define and assign the array at the same time. The length (5) is defined automatically.
int[] a = {1, 2, 3, 4, 5}; // Shorter form that does the same for pre-defined array
Accessing Elements in Arrays

Array elements are accessed using index numbers, which start from 0. For instance, a[0] refers to the first item, a[1] refers to the second item, and so on.

int[] a = {1, 2, 3, 4, 5};
System.out.println(a[0]); // Output: 1
System.out.println(a[2]); // Output: 3
// System.out.println(a[5]); // Error - there is no such element in the array

Keep in mind that an array has a fixed size. Therefore, attempting to access a[5] or any index beyond would lead to an error.

Array Properties and Methods
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal