Array

What is array?
  • Array is a collection of similar type of elements that have contiguous memory location.
  • We can store only fixed set of elements in an array.
  • Array is index based, first element of the array is stored at 0 index.
  • There are two types of array in java software development language. One Dimensional Array and Two Dimensional Array.
1) One dimensional array:
One dimensional array is just like spreadsheet with data in one row

Java array
Syntax:
dataType[] arr; (or)  
dataType []arr; (or)  
dataType arr[];

Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class ArrayDemo {
 public static void main(String args[]) {
  int a[] = new int[5];// declaration and instantiation

  a[0] = 10;// initialization
  a[1] = 20;
  a[2] = 70;
  a[3] = 40;
  a[4] = 50;

  // printing array
  for (int i = 0; i < a.length; i++)// length is the property of array
   System.out.println(a[i]);
 }
}
Output
10
20
70
40
50

Another way of creating and initializing same one dimensional array is as shown below.
      int a[]={10,20,70,40,50};

2) Two Dimensional Array:
  • Two dimensional array in java software development language is just like spreadsheet with multiple rows and columns having different data in each cell. 
  • Each cell will be identified by it's unique row and column index combination (Example str1[3][2]). 
Java array
  • We can use two dimensional array to store user id and password of different users as shown in above Image. 
  • For above given example Image, We can create and initialize values in two dimensional array as shown in bellow given example.
Syntax:
dataType[][] arrayRefVar; (or)  
dataType [][]arrayRefVar; (or)  
dataType arrayRefVar[][]; (or)  
dataType []arrayRefVar[];   

Example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class TwoDimensionalArray {
 public static void main(String[] args) {
  String str[][] = new String[3][2]; // 3 rows, 2 columns

  str[0][0] = "user_1";
  str[1][0] = "user_2";
  str[2][0] = "user_3";
  str[0][1] = "pwd_1";
  str[1][1] = "pwd_2";
  str[2][1] = "pwd_3";

  for (int i = 0; i < str.length; i++) {// This for loop will be total executed 3 times.
   for (int j = 0; j < str[i].length; j++) {// This for loop will be executed for 2 time on every iteration.
    System.out.println(str[i][j]);
   }
  }
 }
}



<-- Previous || Next -->

No comments:

Post a Comment