Click here to Skip to main content
15,914,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is the difference between following 2 approaches in creating an array.
Which is preferred depending on the use?

Approach 1:


int a[]= new int[5];
a[0] = 98;
a[1] = 97;
a[2] = 99;
a[3] = 94;
a[4] = 96;

Approach 2:
int a[]={98,97,99,94,96};

What I have tried:

I tried both the ways bu want to know which one way is better based on the use?
Posted
Updated 19-Dec-18 1:36am

There should be no difference as far as I know. Yet approach 2 is better looking, in my opinion.
 
Share this answer
 
Why don't you try and see for yourself? In the first approach, you are creating the array and initializing it with the values in the same go.

In the first approach, you are creating the array—int is a primitive type, thus they are not null-ed, and you end up with object creation and defaulted to zero. Try this code,
Java
int[] array = new int[5]; // Defaults to 0
        
System.out.println(array[3]); // 4th object exists; 0.
// Outputs 
// 0
The second approach is both, readable and good for the JVM, in this, you create the array and initialize it with the default values.
int[] array =  { 1, 2, 3, 4, 5 };
        
System.out.println(array[3]);
// Outputs 
// 4
This means that JVM setup things for you. To make things simple, they are both the same as,
Java
int a;
a = 5;

// And
int a = 5;
Which one is better? First one is good if you do not know the value at the declaration time, and second is better if you know. Second approach would be redundant call (as per compiler), if you also have to take the input and set it in the next call. I leave that choice in your hand.

In my opinion, go for the second approach, unless you are taking input from the users for each element then it makes sense to initialize the array and read the input from a stream. Other than that, I would always appreciate the code that has second approach.

You can play with this online, http://tpcg.io/wPt4ZI.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900