Array in Java

An array in Java is a collection of values having contiguous memory locations and share a common name.
Suppose you want to create an array of five numbers having data type integer and array name in num.
So, first you need to declare as
int num[];

Second, you need to allocate memory using new operator see the statement

num= new int[5];

The above statement allocates memory in contiguous locations.
Now array is created you can assign values to the array;

num[0]=10;
num[1]=20;
num[2]=30;
num[3]=40;
num[4]=50;

Now you can print values using the below statements.
System.out.println(num[0]);
System.out.println(num[1]);
System.out.println(num[2]);
System.out.println(num[3]);
System.out.println(num[4]);

See the whole program

public class Ar
{
public static void main(String args[])
{
int num[];
num= new int[5];
num[0]=10;
num[1]=20;
num[2]=30;
num[3]=40;
num[4]=50;
System.out.println(num[0]);
System.out.println(num[1]);
System.out.println(num[2]);
System.out.println(num[3]);
System.out.println(num[4]);

}
}

Output:
10
20
30
40
50

Array-in-Java
The same program can be written using for loop
See below

import java.util.Scanner;
public class Ar
{
public static void main(String args[])
{
int num[];
num= new int[5];
int n=num.length;
Scanner s= new Scanner(System.in);
for(int i=0; i < n; i++)
{
num[i]=s.nextInt();
}
for(int i=0; i < n; i++)
{
System.out.println(num[i]);
}

}
}

Output:
10
20
30
40
50

Java's Array

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.