Java Array (With Examples)
Java Array (With Examples)
Here, the above array cannot store more than 100 names. The
number of values in a Java array is always fixed.
dataType[] arrayName;
For example,
double[] data;
// declare an array
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the
size or length of the array is 10.
Note that we have not provided the size of the array. In this case,
the Java compiler automatically specifies the size by counting the
number of elements in the array (i.e. 5).
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
:
Java Arrays initialization
Note:
Array indices always start from 0. That is, the first element
of an array is at index 0.
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
Output
We can use loops to access all the elements of the array at once.
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
Output
:
Using for Loop:
12
4
5
In the above example, we are using the for Loop in Java (/java-
programming/for-loop) to iterate through each element of the
array. Notice the expression inside the loop,
age.length
Here, we are using the length property of the array to get the size
of the array.
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
Output
As you can see, we are converting the int value into double . This
is called type casting in Java. To learn more about typecasting,
visit Java Type Casting (/java-programming/typecasting).
Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional
arrays. However, we can declare multidimensional arrays in Java.
Also Read:
Challenge:
Check Code
:
Next Tutorial: (/java-
Java Multidimensional programming/multidimensional-
Arrays array)
Previous Tutorial:
(/java-programming/switch-statement)
Java switch Statement
Share on:
(h!ps://www.facebook.com/sharer/sharer.php? (h!ps://twi!er.com/inten
u=h!ps://www.programiz.com/java- text=Check%20this%20a
programming/arrays) programming/arrays)