DEV Community

Calin Baenen
Calin Baenen

Posted on

What's the difference between including `new type[]` and not including it?

I know it's needed when making an array with no initial value, but, what's the difference between

char[] carr = {'a', 'b', 'c', 'd'};
Enter fullscreen mode Exit fullscreen mode

and

char[] carr = new char[] {'a', 'b', 'c', 'd'};
Enter fullscreen mode Exit fullscreen mode

?

Top comments (1)

Collapse
 
190245 profile image
Dave

The difference is simply that in one form, you have less typing, and the person reviewing your code has less reading.

That's it, it's just syntax. They will both actually create a new array in memory.

But maybe this needs to get a little "off-piste", and this is only really referenced because you're using an array of char... you should probably consider String (speed vs memory usage trade-off). In most situations, an array of char is simply faster, but if you have a lot of them, and don't access them all that often, String gets better memory management in Java.

Consider the following code:

public class TestForDev {

    public static void main( String[] args ) {
        char[] carr = {'a', 'b', 'c', 'd'};
        char[] otherButSame = {'a', 'b', 'c', 'd'};
        char[] createdWithNew  = new char[] {'a', 'b', 'c', 'd'};

        String someString = "test";
        String anotherString = new String("test");
        String aThirdString = "test";
        System.out.println("Don't use System.out!");
    }
}
Enter fullscreen mode Exit fullscreen mode

How many objects are created? If I look in my IDE:
screenshot of char array
We have 3 unique objects (given away by the numbers after the @ symbol).

Now for String, it's actually backed by a char array...
screenshot of Strings
Note that they all have the same Object ID, so we have 3 references to the same object.

Memory management is something that a lot of Java developers (at all levels) simply don't think about, but we should, in my opinion.