aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes anonymous array size (define or not define?) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "anonymous array size (define or not define?)" Watch "anonymous array size (define or not define?)" New topic
Author

anonymous array size (define or not define?)

sarah mrinmoyee
Greenhorn

Joined: Jul 12, 2012
Posts: 8
In k&b book, its said that when using anonymous array, you do not use array size.

for example:

int[] anonymousArray;

new int[3]{someVal1, someVal2, someVal3}; // is illegal

but if i do this,

new int[2]; // it works fine.


So what is the catch?? Is it illegal to define size or recommended not to define?
I used as following:

public class MyAnonymous{

public void testMethod1(){
testMethod2(new int[2][]);

}


public void testMethod2(int[][] b){

...
}

public void main(Strings args[]){
//call to testMehtod1()
}


}


As far i understood if you define size and also use number of items {val1,val2} it does not compile.


Any idea guyz/gals??




- Sarah
Bhavesh Saraswat
Greenhorn

Joined: Jan 20, 2013
Posts: 18

Hi Sarah,

at the time of initialization size of the array is used to create array object. There are two ways to define the size of the array -

-- one way is to define size in the square braces without defining any element at creation time.

-- another way is to define array elements and it automatically counts the size of array to be created. In this way size of the array should not be provided.

I hope you are clear with your ques.


OCPJP SE6
Dan Drillich
Ranch Hand

Joined: Jul 09, 2001
Posts: 1179
Hi Sarah,

As you can see in Array Declaration, Construction, & Initialization (Objective 1.3) there are three stages for their definitions.


Belongs to the declaration stage where size is not allowed.

Belongs to the construction of an array object where the size is mandatory.

Regards,
Dan



William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
sarah mrinmoyee
Greenhorn

Joined: Jul 12, 2012
Posts: 8
Thank you Guys,

But isn't "new int[2]; " // here size is not mandatory if you 't provide values like new int {0,1,2 }.

Actually i was confused with the line "when you use anonymous array size should not be defined!" It should be like if you provide values to the array then don't use size. But i am fine with the array declaration and initialization.

Keep posting!
-sarah
 
Consider Paul's rocket mass heater.
 
subject: anonymous array size (define or not define?)