To create a 2-D array or multidimensional Array we have to specify the base size of the Array.Because we are using new operator for allocating memory to array so Compulsory we should provide size at least base.For Array, creation java follows Array of Array Approach.
example 1:
x[ 0] =new int [2];
x[1] =new int [3];
Memory representation of above example:
example 2:
int [ ] [ ][ ] x =new int [ 3] [ ] [ ]; (valid)
In the above example, we provided the base value 3. Rest of we kept empty which is valid in java.
we won't get any compile time error or runtime exception;
example 3:
int [ ] [ ] x = new int [ ] [ 2]; (invalid)
In the above example we did' provide any base value,means base index is empty so it is wrong in java.
Hence we will get Compile time Error.
Que:
which of Array Declaration are valid?
int [ ] a =new int [ ];
int [ ] a =new int [ 3];
int [ ] [ ] a =new int [ ] [ ];
int [ ] [ ]a =new int [ 2] [ ];
int [ ] [ ]a =new int [ ] [ 4];
int [ ] [ ]a =new int [ 2] [3 ];
int [ ] [ ] [ ]a =new int [ 2] [ 4] [ 5];
int [ ] [ ] [ ]a =new int [ ] [ 1] [2 ];
int [ ] [ ] [ ]a =new int [ 2] [ ] [3 ];
Now scroll down for check your answers;
Ans
int [ ] a =new int [ ]; (invalid)
int [ ] a =new int [ 3]; (valid)
int [ ] [ ] a =new int [ ] [ ]; (invalid)
int [ ] [ ]a =new int [ 2] [ ]; (valid)
int [ ] [ ]a =new int [ ] [ 4]; (invalid)
int [ ] [ ]a =new int [ 2] [3 ]; (valid)
int [ ] [ ] [ ]a =new int [ 2] [ 4] [ 5]; (valid)
int [ ] [ ] [ ]a =new int [ 2] [ 4] [ 3]; (valid)
int [ ] [ ] [ ]a =new int [ ] [ 1] [2 ]; (invalid)
int [ ] [ ] [ ]a =new int [ 2] [ ] [3 ]; (valid)
No comments:
Post a Comment
Be the first to comment!
Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.
Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
Regards,
JavaByChetan
Back To Home