Вы находитесь на странице: 1из 1

2 DIMENISIONAL

ArRay
2D ARRAY
Two – dimensional array is
the simplest form of a
multidimensional array. A
two – dimensional array can
be seen as an array of one –
dimensional array for easier
understanding.

SYNTAX
How to Declare
2 Dimensional
Declaration – Syntax:
Array
data_type[][] array_name = new data_type[x][y]; in Java
For example: int[][] multiples = new int[4][2];
int[][] arr = new int[10][20]; // 2D integer array with 4 rows and
2 columns

String[][] cities = new String[3][3];


// 2D String array with 3 rows and 3

Initialization – Syntax: columns

array_name[row_index][column_index] = value; int[][] wrong = new int[][];

EXAMPLE 
For example: arr[0][0] = 1; // not OK, you must specify 1st dimension

int[][] right = new int[2][];


class TwoDimensionalArray { // OK
public static void main(String[] args) {

String[][] salutation = { How to Loop and Print 2D


{"Mr. ", "Mrs. ", "Ms. "},
{"Kumar"} array in Java
};
// Mr. Kumar
System.out.println(salutation[0][0] + salutation[1][0]);
// Mrs. Kumar If you want to access each
System.out.println(salutation[0][1] + salutation[1][0]);
} element of a two-dimensional
The output from this }
array, then you need to iterate
program is:
through the two-dimensional
Mr. Kumar array using two for loops.
Mrs. Kumar
Why? because you need two
indexes to access an individual
element from the 2D array.
You can either use  advanced
for each loop  or  classic for
loop with a counter

Вам также может понравиться