Accessing Elements of an Array in Java

We can access the element of an array using the index number. Here is the syntax for accessing elements of an array,


\begin{lstlisting}
// access array elements
array[index]
\end{lstlisting}

Let's see an example of accessing array elements using index numbers.


\begin{lstlisting}
class Main {
public static void main(String[] args) {
\par
/...
...ge[3]);
System.out.println(''Fifth Element: '' + age[4]);
}
}
\end{lstlisting}

The output for the above code block will be


\begin{lstlisting}
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5
\end{lstlisting}

In the above example, notice that we are using the index number to access each element of the array. We can use loops to access all the elements of the array at once.