Array in Java

As in life we experience and come across new technologies, bits of information and etc , we usually sometime dont concern or overlook about little or small units in every context of life.

Working with array sound simple but i was myself not aware of so many different ways to initialize Arrays in Java, MUST read and understand the third way of declaring Java Arrays!

Method #01

  1. int[] myArray1 = new int[3];
  2. int[] myArray2 = {1,2,3};
  3. int[] myArray3 = new int[]{1,2,3};

Method #02

  1. int myArray4[] = new int[3];
  2. int myArray5[] = {1,2,3};
  3. int myArray3[] = new int[]{1,2,3};

Although Method #01  and Method #02 looks different but when it comes to compiler they both are similar. The difference is just the positioning of brackets.

Here comes the mystery!

Method #03

  1. int []myIntArray5 , ab = {1,2,3};     // Although it seems to us we have one myIntArray of Array type and ab of Int type , but its not the case ab here is also a One Dimensional Array with Values Initialized to 1,2,3
  2. float invt[][];                                        // invt of Type Float  and a 2-dimenionsal Array
  3. float []prct, grts[];                              // prct one dimensional array and  grts is TWO dimensional array
  4. float [][] sms ,  hms[];                       //  sms is two dimensional array where hms is THREE dimensional array
  5. float[]  []sms[] ,  hms[];                    // sms and hsm are both THREE dimensional array
  6. float[]  []sms[] , [] hms[];                //  sms is THREE dimensional array but hms will Produce a compile time error! i.e identifier expected after ,  (Comma)

Print Array Elements

In Java 5 Arrays.toString(arr) or Arrays.deepToString(arr) for arrays within arrays. Note that Object[] version calls .toString() of each object in array. If my memory serves me correct, the output is even decorated in the exact way you’re asking.


2 thoughts on “Array in Java

  1. Deskhmukh Gaurav May 14, 2013 at 4:53 am Reply

    Anwaar Thanks a lot, even i was not aware of these array initialization and different ways to represent arrays!

  2. Ashok May 14, 2013 at 4:58 am Reply

    Nice Refresher! Thanks

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: