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'};
and
char[] carr = new char[] {'a', 'b', 'c', 'd'};
?
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'};
and
char[] carr = new char[] {'a', 'b', 'c', 'd'};
?
For further actions, you may consider blocking this person and/or reporting abuse
Nathan Rajkumar -
Harshit Singh -
Olga Lugacheva -
Thompson Olufemi -
Top comments (1)
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:
How many objects are created? If I look in my IDE:
We have 3 unique objects (given away by the numbers after the @ symbol).
Now for String, it's actually backed by a char array...
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.