How to create and work with arrays in Java?
How can I create and work with arrays in Java?
Content writing is the process of writing, editing, and publishing content in a digital format. That content can include blog posts, video or podcast scripts, ebooks or whitepapers, press releases, product category descriptions, landing page or social media copy and more.
Aryan Kumar
09-Sep-2023In Java, an array is a data structure that can store a collection of data of the same type. Each element in the array has a unique index, starting from 0.
To create an array in Java, you need to use the
new
keyword. The syntax to create an array is:where
datatype
is the type of data the array will store,arrayName
is the name of the array, andlength
is the number of elements the array will contain.For example, the following code creates an array of integers named
numbers
with 5 elements:You can also initialize an array while creating it. To do this, you can use the curly braces to enclose the initial values of the array elements. For example, the following code creates a string of strings named
names
with 3 elements and initializes the first element to "John", the second element to "Jane", and the third element to "Peter":Once you have created an array, you can access its elements using their indexes. The index of the first element is 0, the index of the second element is 1, and so on.
To access an element in an array, you can use the following syntax:
For example, the following code prints the value of the first element of the
numbers
array:You can also change the value of an element in an array. To do this, you can use the following syntax:
For example, the following code changes the value of the first element in the
numbers
array to 10:You can also iterate through the elements of an array using a for loop. The following code loops through the elements of the
numbers
array and prints each element to the console:Here are some other things to keep in mind when working with arrays in Java:
ArrayIndexOutOfBoundsException
will be thrown.length
property of an array to know its size.