Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'new' for arrays in Java

Tags:

I've been undertaking some basic tutorials. One of which has asked me to set up an array to hold the following string values:

Beyonce (f) David Bowie (m) Elvis Costello (m) Madonna (f) Elton John (m) Charles Aznavour (m) 

Write a program to loop round, count how many are male vocalists and how many are female, and display my answer in the console.

I managed to complete it, but the way I set up my array was different to the answer provided.

Mine is as follows:

String names[] = {"Beyonce (f)", "David Bowie (m)", "Elvis Costello (m)", "Madonna (f)", "Elton John (m)", "Charles Aznavour (m)"}; 

And the provided answer is as such:

String[] singers = new String[6]; singers[0] = "Beyonce (f)"; singers[1] = "David Bowie (m)"; singers[2] = "Elvis Costello (m)"; singers[3] = "Madonna (f)"; singers[4] = "Elton John (m)"; singers[5] = "Charles Aznavour (m)"; 

Should I be creating a "new" array? If so, why? And what is the difference between the two?

like image 717
javapalava Avatar asked Jan 20 '15 10:01

javapalava


People also ask

Why do we use new for array in Java?

Well, in Java new is necessary for every Object allocation, because in Java all objects are dynamically allocated. Turns out that in Java, arrays are objects, different from C/C++ where they are not. Voting is disabled while the site is in read-only mode.

What is the use of new keyword in array?

To create an array value in Java, you use the new keyword, just as you do to create an object. Here, type specifies the type of variables (int, boolean, char, float etc) being stored, size specifies the number of elements in the array, and arrayname is the variable name that is the reference to the array.

What is new array in Java?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: String[] cars; We have now declared a variable that holds an array of strings.

Is it necessary to use new operator to initialize an array?

JAVA Programming Array can be initialized when they are declared. Array can be initialized using comma separated expressions surrounded by curly braces. It is necessary to use new operator to initialize an array.


1 Answers

Your answer is equivalent but more readable and less error-prone because you don't need any "magic numbers" for each array element with the "fear" of accessing an element out of the array definition and therefore creating an IndexOutOfBoundsException.

like image 167
Smutje Avatar answered Oct 02 '22 10:10

Smutje