Quan Nguyen Quan Nguyen - 1 month ago 4x
Java Question

String[] names = String[0]; is this valid?

I tested on this website:

String[] names =new String[0];

The result says this is valid, but when I test it on IDE, I get an error. Someone tell me why?

String[] names = new String[0]; 

is a valid statement (as the web-quiz that you mention suggests), even if I question its usability, since it creates an array of zero length, so you cannot add any elements to it...

The error that you imply (I think) in your comment

"If creating an array of type String and size 0. I think names variable is not used. we can not assign a value to names variable. thanks"

in Amit Bhati's (perfectly valid) answer, is not an error.

"Variable not used" is a warning, telling you that you declare something that you never use. In other words, you do not assign any values to this array. The warning will be gone, if you actually use the names variable afterwards and assign a value to it (even if it makes no sense, since it has 0 length).

For example:

names[0] = "something";

This will turn the IDE warning into a runtime problem, though...

EDIT: As for WHY java allows the declaration of a 0-length array, you can follow this post.