1

If arrays are objects in Java then why they are not initialized using syntax X x = new X();?

Like if there is a class named Person, and I have to create an object of that class then I will use syntax: Person p1 = new Person();. So why we don't declare arrays in the same way?

Please explain, arrays should be initialize using that syntax.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Does this answer your question? [How do I declare and initialize an array in Java?](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) – happy songs Mar 24 '23 at 13:45
  • 1
    You seem to be under impression that objects in Java are only class instances. That is not true. There are **two** kinds of objects in Java: (1) class instances, and (2) arrays - which are separate from class instances, so they can follow different syntax. The `new ClassName(arguments)` syntax is for creating instance of `ClassName`. For arrays we can use for instance `new TypeName[size]`, but there are also other ways like `String strArray = {"abc", "def"};`. – Pshemo Mar 24 '23 at 14:02
  • 1
    Because that's how the language is designed. Please read [this](https://meta.stackoverflow.com/a/323382/5133585), and [edit] your question to clarify what kind of answer you are looking for here. – Sweeper Mar 24 '23 at 14:02
  • Arrays are historically pointers, not objects. In a purely functional language, you can have arrays and no objects. Arrays transcend OOP. – Mr. Polywhirl Mar 24 '23 at 14:05
  • Vague title. Rewrite to summarize your specific technical issue. – Basil Bourque Mar 24 '23 at 16:26

1 Answers1

1

You can. While it is allowed to omit new String[] in array declaration, the full syntax is

String[] arr = new String[] { "Hello", "World" };

which is a longer way to write

String[] arr = { "Hello", "World" }; // This is only valid at declaration time.

both are just a shorter way to write

String[] arr = new String[2];
arr[0] = "Hello";
arr[1] = "World";
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Note that you cannot do the following, `String[] arr; arr = { "Hello", "World" };`, or else you will get an _"Array constants can only be used in initializers"_ error. The short-hand syntax can only be used in a constant declaration. – Mr. Polywhirl Mar 24 '23 at 14:09