How can I create and work with arrays in Java?
How can I create and work with arrays in Java?
368
05-Sep-2023
Aryan Kumar
06-Sep-2023To create an array in Java, we must first need to declare a variable of the desired array type. The syntax for declaring an array is:
where
datatypeis the type of data that array will hold, andarrayNameis the name of the array.Once you have declared an array variable, you need to allocate memory for the array using the
newkeyword. The syntax for allocating memory for an array is:where
lengthis the number of elements that array will contain.For example, the following code declares an array of integers named
numberswith the length of 10:Once you have created an array, you have to initialize it with values. You can initialize array in two ways:
numberswith the values 1, 2, 3, 4, and 5:numbersone by one:After initializing the array, you can access its elements via index. The first element has index 0, the index of the second element is 1, and so on. For example, the following code prints the value of the first element of the array
numbers:You can also iterate the array through the elements using a for loop. For example, the following code prints the values of all the elements of the array
numbers:Here are some other things to keep in mind about arrays in Java: