Array Initialisation Difference

ZacZac
edited July 2015 in Questions about Code

Is there any difference between (and if so what is it)

String values[] = new String[0];

and

String[] values = new String[0];?

Thanks, Zac

Answers

  • Answer ✓

    The latter is Java style and it's the expected standard style.
    The former is C/C++ style and it's "frowned" upon! :P

  • edited July 2015

    BtW, String[] values = new String[0]; can be replaced w/ String[] values = {};.

  • Answer ✓

    To be clear: no, there is no difference.

    But use the first way. It "reads" better. I want a float array named variable. Not a float named variable... that is an array.

  • Thanks. Guess that means back to the drawing board for debugging :P

  • edited July 2015

    An extra tidbit: using C/C++ style, we can mix up array & regular variables in the same declaration line:
    float value = PI, values[] = { TAU, EPSILON, sqrt(3) };

    So variable value is a regular float; while values is a float[] array! \m/

    But be careful: in the example below, both become arrays:
    float[] value = { PI }, values[] = { { TAU, EPSILON, sqrt(3) } };

    However, while value is a float[] now, values was "upgraded" to a 2D float[][] array! @-)

  • edited July 2015

    I agree you should use the first way because it mirrors the way you declare simple variables

    data-type identifier {= initializer };

    {} optional

    If you want to use the second style then this is OK too, provided you are consistent and don't mix them in the same sketch.

    Java is very flexible so as demonstrated you can mix and match simple variable and array declarations in one statement. This should ALWAYS be avoided because it adds unneccessary complexity to your code which makes it harder to read so will reduce software maintainability, a key attribute of good software.

  • edited July 2015

    And to add more confusion into the Java's flexible syntax, behold the ultimate brain screw: 8-}

    static final String splitByColon(String txt)[] {
      return split(txt, ':');
    }
    

    The utility function above returns a String[] array.
    But try to spot where the [] was placed there! =))

Sign In or Register to comment.