Java Arrays

In computer programming, an array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names.


\begin{lstlisting}
String[] array = new String[100];
\end{lstlisting}

The number of values in the Java array is fixed. That is, the above array can not store more than 100 elements. In Java, here is how we can declare an array.


\begin{lstlisting}
dataType[] arrayName;
\end{lstlisting}

For example,


\begin{lstlisting}
double[] data;
\end{lstlisting}

Here, data is an array that can hold values of type double. But, how many elements can array this hold? To define the number of elements that an array can hold, we have to allocate memory for the array in Java. For example,


\begin{lstlisting}
// declare an array
double[] data;
\par
// allocate memory
data = new Double[10];
\end{lstlisting}

Here, the array can store 10 elements. We can also say that the size or length of the array is 10. In Java, we can declare and allocate memory of an array in one single statement. For example,


\begin{lstlisting}
double[] data = new double[10];
\end{lstlisting}



Subsections