0

While the "normal" syntax for creating an array (lets say for this example an array of type MyClass) in Java is MyClass[] arr = new MyClass[3], I've noticed the next syntax also works:

MyClass arr[] = new MyClass[3]

That surprised me today, since by intuition a program would want a uniform syntax. My question is there is a reason for this syntax?

Is it because of an impact from another language or is it just to offer flexibility? Or, another option is that it is actually not weird and is just weird for me, but I will mention that I haven't seen this type of array deceleration anywhere.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Mickey
  • 1,405
  • 2
  • 13
  • 33

2 Answers2

2

You are almost right (java is different from C/C++ so) following are "Valid" ways to tell the compiler you are talking about an array:

private void name() {
    Object[] arr1 = new Object[3];
    Object arr2[] = new Object[3];
    Object[] arr3 = new Object[] { "", "", "" };
    Object[] arr4 = { "", "", "" };

}

and my "favorite" one (see the header of the method):

private int foo()[]{
    //TODDY
    return new int[] { 1, 2, 3};
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

impact from another language

That's it: C (or C++) - in both languages, arrays are defined in the way you wonder about - the Java way is not valid in these languages, by the way.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59