An array is a group of homogeneous variables. To create an array, you first must create an array variable of desired type.

One Dimensional Array –

General form of a one-dimensional array declaration is –

typevarname[] ;

Here, type declares the base type of the array. The base type determines the data type of each elements that comprises the array. Thus, the base type for the array determines what type of data the array will hold.

Obtaining an array is a two step process. Firstly, we have to declare a variable of the desired array type. Then, we must allocate the memory that will hold the array, using new and assign it to the array variable. That is why,inJava all arrays are dynamically allocated.

Here is a program that creates an array of the number of days in each month.

Java Arrays by Knowledgetpoint

Program

// Demonstrate a one-dimensional array.
 
class Array {
public static void main(String args[]) {
intmonth_days[] ;
month_days = new int[12] ;
month_days[0] = 31;
month_days[1] =28 ;
month_days[2] =31 ;
month_days[3] =30 ;
month_days[4] =31 ;
month_days[5] =30 ;
month_days[6] =31 ;
month_days[7] =31 ;
month_days[8] =30 ;
month_days[9] =31 ;
month_days[10] =30 ;
month_days[11] =31 ;
System.out.println(“April has ” + month_days[3] + “days”) ;
}
}

Output –

When we will run this program, it will print the days in April. The reason being that in Java array indexes start with zero, and thus the output will be April has 30 days.

Multi Dimensional Array –

Recommended Post   Java Enumerations

It is basically arrays of arrays. There are a difference between between 1-D array and a multi dimensional array.

To declare a multidimensional array variable, each additional index is to be specified using another set of square brackets .

For eg

A 2-D array –

InttwoD [] [] = new int [3] [4] ;

This will allocate a 3 by 4 two-D array. Internally, it will be implemented as an array of arrays of int.

What is array data structure in Java?

A simple program on a 2-D array

Program

// Example of a two-dimensonalarray .

class TwoDArray {

public static void main(String args[]) {

intab[] [] = new int [3][4] ;

int i, j, k = 0 ;

for (i=0; i<3; i++)

for (j=0; j<4; j++)

{ ab[i] [j] = [k] ;

k++

}

for (i=0; i<3; i++) {

for (j=0; j<4; j++)

System.out. println ( ab[i] [j] +” ”) ;

System.out. println() ;

}

}

}

Output –

This program will generate the following output –

0 1 2 3

4 5 6 7

8 9 10 11

 

 

 

 

 

 

 

 

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here