Java: Declaring array with a particular size

Hello Experts!

Java newbie here. :)

in C, I am used to declaring arrays with a particular size

e.g.
int mileages[3];

Open in new window

Java apparently does not let me do so, but allowed me to do:

int mileages = {1, 4, 10};

Open in new window


In researching  this issue online I found:
int[] myIntArray = new int[3];// Example #1
int[] myIntArray = {1,2,3}; // Example #2

Open in new window


So my questions are specifically the following:

1. If I am declaring an array with a specific length per #1, is it mandatory to include the new keyword, and/or the []'s after int?

2. For #2,, can I leave out the [] after the int  I assume I can b/c Java allowed:
int mileages = {1,4,10};

Open in new window



Thanks,
Steve
LVL 4
Stephen KairysTechnical Writer - ConsultantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Margaret GreenCommented:
int is a primitive type like float, double or boolean for instance.

An array is an object. It contains a fixed number of elements of a  type -- a primitive type or an object type.

int[] is declaration of an object, not a primitive type. So the answer to point 2. in the question is no you cannot.  It is an assignment of type initialized array to a primitive.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Stephen KairysTechnical Writer - ConsultantAuthor Commented:
Margaret,

>>So the answer to point 2. in the question is no you cannot.  It is an assignment of type initialized array to a primitive.<<

Thank you. My bad. I did indeed say:
int mileages[] = {4, 6, 10, 26};
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.