-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathCreating and Initializing 1D,2D Arrays
36 lines (28 loc) · 1.55 KB
/
Creating and Initializing 1D,2D Arrays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
In the below mentioned program, we undersand two things:
1. This is to understand creating and initializing 1D, 2D arrays. Doing initialization and creation in the same step,
does not require 'new' operator. PLEASE UNDERSTAND CAREFULLY, how this is done.
2. We also understand, how to access the number of rows and columns in 2D arrays. PLEASE UNDERSTAND CAREFULLY.
package forTesting;
public class SingleAndMultiDimentionalArraysInitialization {
public static void main(String[] args) {
// Initializing single dimensional arrays. Doing initialization and creation in the same step, does not require 'new' operator.
String[] OneDArray = {"hello","world","my","name","is"};
int[] intArray = {1,2,3,4,5,6,7,8};
// Initialzing 2d array. Doing initialization and creation in the same step, does not require 'new' operator.
String[][] TwoDArray = {{"hello","world"},{"hi","bye"},{"me","tu"},{"aapli","aapla"}}; // 4*2 array
int[][] intTwoArray = {{1,2,3},{4,5,6},{8,9,10},{11,12,13},{14,15,16}}; // 3*5 array
//Use 2D array
int[][] maze = new int[6][6];
maze[0] = new int[] { 1, 1, 0, 0, 0, 0 };
maze[1] = new int[] { 0, 1, 0, 0, 0, 0 };
maze[2] = new int[] { 0, 1, 0, 1, 1, 1 };
maze[3] = new int[] { 1, 1, 1, 1, 0, 1 };
maze[4] = new int[] { 0, 1, 0, 0, 0, 1 };
maze[5] = new int[] { 0, 1, 0, 0, 0, 1 };
// Accessing number of rows and columns in multidimentional arrays
int rows = TwoDArray.length; // Gives number of rows
int columns = TwoDArray[0].length; // Gives number of coulmns
System.out.println(rows);
System.out.println(columns);
}
}