How can I create and work with arrays in Java?
How to create and work with arrays in Java?
525
07-Sep-2023
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
newkeyword. The syntax to create an array is:where
datatypeis the type of data the array will store,arrayNameis the name of the array, andlengthis the number of elements the array will contain.For example, the following code creates an array of integers named
numberswith 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
nameswith 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
numbersarray: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
numbersarray 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
numbersarray and prints each element to the console:Here are some other things to keep in mind when working with arrays in Java:
ArrayIndexOutOfBoundsExceptionwill be thrown.lengthproperty of an array to know its size.