Search code examples
javaarraysnew-operator

When should I use "new" when creating an array in Java?


I would like to understand the difference the "new" command does in the line 2 in code below. Because when I print the positions, the answer is the same. So I don't see the necessity to use this "new" command.

float[] values = { 10, 20, 30, 40, 50 }; //In my view the easy way to do it
float[] values2 = new float[] { 10, 20, 30, 40, 50 }; //not understand why more verbose?

I just made a research and found some explain related to heap memory and pool. However I didn't understood why and when should use the new and when shouldn't.


Solution

  • This is known as an "Array Initializer". It's a shorthand (syntactic sugar) introduced in JDK 5 that has existed since 1.0 (credit to Andy and Holger below).

    float[] values = { 10, 20, 30, 40, 50 };
    

    The latter is the traditional way to assign an array.

    float[] values2 = new float[] { 10, 20, 30, 40, 50 };
    

    You can use whichever makes you feel more comfortable.


    Keep in mind that the shorthand is only allowed during initialization.

    public class ArrayInitializer {
        public static void main(String[] args) {
            float[] values;
            values = new float[] { 10, 20, 30, 40, 50 }; // Valid
    
            float[] values2;
            values2 = { 10, 20, 30, 40, 50 }; // Invalid
        }
    }