Array In Java

[1]. Declare and define an array

       int intArray[] = new int[3];

This will create an array of length 3. As it holds a primitive type, int, all values are set to 0 by default. For example,

        intArray[2]; // Will return 0

[2]. Using box brackets [] before the variable name

      int[] intArray = new int[3];
    intArray[0] = 1; // Array content is now {1, 0, 0}


[3]. Initialise and provide data to the array

       int[] intArray = new int[]{1, 2, 3};

 This time there isn't any need to mention the size in the box bracket. 

Even a simple variant of this is:

           int[] intArray = {1, 2, 3, 4};
     An array of length 0
     int[] intArray = new int[0];
     int length = intArray.length; // Will return length 0

Similar for multi-dimensional arrays

           int intArray[][] = new int[2][3];
     // This will create an array of length 2 and
     //each element contains another array of length 3.
     // { {0,0,0},{0,0,0} }
     int lenght1 = intArray.length; // Will return 2
     int length2 = intArray[0].length; // Will return 3

Using box brackets before the variable:

      int[][] intArray = new int[2][3];

It's absolutely fine if you put one box bracket at the end:

        int[] intArray [] = new int[2][4];
    int[] intArray[][] = new int[2][3][4]

Some examples

     int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
   int [] intArray1 [] = new int[][] {new int[] {1,2,3}, 
                        new int [] {4,5,6}};
   int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
  // All the 3 arrays assignments are valid
  // Array looks like {{1,2,3},{4,5,6}}

It's not mandatory that each inner element is of the same size.

    int [][] intArray = new int[2][];
   intArray[0] = {1,2,3};
   intArray[1] = {4,5};
   //array looks like {{1,2,3},{4,5}}

      int[][] intArray = new int[][2] ; 
  //This won't compile. Keep this in mind.

You have to make sure if you are using the above syntax, that the forward direction you have to specify the values in box brackets. Else it won't compile. Some examples:

    int [][][] intArray = new int[1][][];
    int [][][] intArray = new int[1][2][];
    int [][][] intArray = new int[1][2][3];

Another important feature is covariant

    Number[] numArray = {1,2,3,4};   // java.lang.Number
   numArray[0] = new Float(1.5f);   // java.lang.Float
   numArray[1] = new Integer(1);    // java.lang.Integer
   // You can store a subclass object in an array that is declared
   // to be of the type of its superclass.
   // Here 'Number' is the superclass for both Float and Integer.
   Number num[] = new Float[5]; // This is also valid


Comments

Popular posts from this blog

Java : Variables Declaring

Install DNF in RHEL/CentOS 7

SQL Self JOIN