An array is a data structure that holds a fixed number of values in contiguous memory locations. Each value in an array is called an element, and each element has a corresponding index.
The length of an array is fixed when the array is created. To retrieve an item from an array, we need to know the index of the item. Java arrays are zero-based, meaning that the first element in the array is at the index 0
and the last element is at index length - 1
.
To retrieve an item from an array, we can use the square brackets notation:
For example, if we have an array named myArray
, we can retrieve the first element by using myArray[0]
and the second element by using myArray[1]
.
If we try to access an item in an array with an index that does not exist, we'll get an ArrayIndexOutOfBoundsException
.
To update an element into an array, we can use the same square bracket notation. For example, to update the first element of myArray
to the value of the variable newValue
, we can use:
We can delete an element from an array by setting the value of the item to null
. For example, if we have an array named myArray
, we can delete the first element by using:
To clear the content of an array, we can use the following code:
The code example below demonstrates various operations on an array:
import java.util.Arrays;class HelloWorld {public static void main( String args[] ) {// Retrieve an item from an arrayint myArray[] = new int[]{1,2,3};System.out.println(myArray[0]); // Outputs 1// Update an item in an arraymyArray = new int[]{4, 5, 6};myArray[0] = 7;System.out.println(Arrays.toString(myArray)); // Outputs {7,5,6}// clearing an arraymyArray = null;System.out.println(Arrays.toString(myArray)); // Outputs null}}
In the code above, we first create an array of integers named myArray
. We then retrieve the first element from the array and print it to the console. Next, we update the entire array with new values and then update the first element to a new value, 7
. Finally, we clear the entire array by setting it to null
.
Free Resources