-4
String arr[3] = {"hello", "liubo"};     // Wrong writing

String arr[] = {"hello", "liubo"};       // Right writing

Why doesn't Java allow developers to specify the array size in advance?

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
  • Maybe it does, but only if you give the same number of strings as you wrote. – mkrieger1 May 07 '22 at 08:52
  • You can do this: String[] stringArray3 = new String[3]; And then: stringArray3[0] = "hello"; stringArray3[1] = "liubo"; – zitrusire2520 May 07 '22 at 08:53
  • I want to explain this problem from the perspective of compiler, but I can't provide a reasonable explanation – China-liubo May 07 '22 at 09:00
  • I strongly recommend that you put the array specifier immediately after the type (`String[] arr`). That is the normal and accepted way to declare arrays in Java. The fact it allows it after the variable name is a historic mistake. – Mark Rotteveel May 07 '22 at 09:00
  • It's quite simple, in Java `String[] arr` (or `String arr[]`, which you shouldn't use) only specifies that the variable `arr` is an array of String. The length is a property of the value referenced by that variable, not of the variable it self. – Mark Rotteveel May 07 '22 at 09:01
  • Related: [How can I define an array with length and some of elements' value in Java?](https://stackoverflow.com/questions/23444996/how-can-i-define-an-array-with-length-and-some-of-elements-value-in-java) – Mark Rotteveel May 07 '22 at 09:03

0 Answers0