Wednesday, December 30, 2009

Java String array - Single and Multidimensional

In java arrays can be single as well as multi dimentional. This is true not only for Strings, but also for int, double, char etc all datatypes.
Arrays can be declared in two ways. Today i will show you how to declare arrays in Java.
This post will cover both the ways array can be declared and also how to access the elements.
Please comment if this post helps you or if there is something I missed.
Happy Coding.

Lets start with Single Dimension Arrays:





 String [] OneDArray1 = new String[10];
  OneDArray1[0] = "1";
  OneDArray1[2] = "2";
  OneDArray1[5] = "3";

  for(int i=0;i
   System.out.println(OneDArray1[i]);
  }
  
Output of this code snippet:

 1
 null
 2
 null
 null
 3
 null
 null
 null
 null



Another way of declaring single dimension arrays:


 String [] OneDArray2 = {"1","2","3"};
  
  for(int i=0;i
   System.out.println(OneDArray2[i]);
  }
  
Output of this code snippet:

 1
 2 
 3
 

Multi Dimensional Arrays


  String TwoDArray1[][] = new String[2][3];
  
  TwoDArray1[0][0] = "1";
  TwoDArray1[0][1] = "2";
  TwoDArray1[0][2] = "3";
  
  TwoDArray1[1][0] = "4";
  TwoDArray1[1][1] = "5";
  TwoDArray1[1][2] = "6";
  
  for(int i=0;i
   for(int j=0;j
    System.out.println(TwoDArray1[i][j]);
   }
  }

Output of this code snippet:

 1
 2
 3
 4
 5
 6
 

Another way of declaring multi dimensional arrays:


 String TwoDArray2[][] = { {"1","2"},{"3","4"} };
  
  for(int i=0;i
   for(int j=0;j
    System.out.println(TwoDArray2[i][j]);
   }
  }
 
Output of this code snippet:
 1
 2
 3
 4



No comments: