Monday 8 July 2013

ARRAY EXAMPLE IN JAVA

Hello Friends,
                        It is very common to have objective question about Array creation in any competition exam.
and it is also possible to be confused and do mistake. 
So here I am giving you an program as an example.
This program illustrate correct as well as incorrect array syntax :



public class ArrayExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        //first way to create array. declairing,constructing and initializing in the same line
    int[] array1={1,2,4,6};
   
     //retrieving array elements
    for(int i=0;i<array1.length;i++)
    {
    System.out.println(array1[i]);
    }

    //second way to create array
    //declaire and construct an array
    int[] array2;
     array2 = new int[3];
 
     int x= -2;
     array2[x] = 7;
     System.out.println(array2[x]);
       //  Run time exception

   
   
     //it is not valid to give size at the time of declaration
   
    int[3] array3;
   
     //so above statement gives compilation error.
   
     int[] array4 = new int[3];
     byte b = 4;
     char c = 'a';
     short d = 7;
     array4[0] = b;
     array4[1] = c;
     array4[2] = d;
     for(int i=0; i<array4.length;i++)
     {
         System.out.println(array4[i]);
         
     }
 

     // constructing Multidimentional array
    String array2d[][] = new String[3][];
    //this is a valid syntax but
   
     String sw1[][] = new String[][3];
    //is not valid .
   
   
    //Second way to create 2-d array
    String array2d1[][] = {   {"ram","shiv","bholenath"}, {"o","m","n","a","m"}};
   
    //Second way to initialize 2-d array
    int array2d3[][] = new int[3][];
    array2d3[0]= new int [2];
    array2d3[0][0]=6;
    array2d3[0][1]=7;
   array2d3[0][2]=9; 

// run time exception 
    array2d3[1]= new int [1];
    array2d3[1][0] = 3;
    }

}

Friends just copy and paste this code and save the file ArrayExample.java , and Run it.
Code in blue colour work correctly but code in red colour gives u error.  So comment the code in red and then run it. and look carefully because it may lead you to a mistake.


Thank you ..........

No comments:

Post a Comment

Search This Blog

Total Pageviews