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!
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:
Consider numbers
as a box with 5 compartments, each holding a number. Simple, isn't it?
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:
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:
