1

I was watching a Udacity video and I realized they declared their arrays a bit different than I did. The way they created their arrays was:

String words[] = new String[] {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

and the way I usually declare it is

String words[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

My guess would be when the "new" keyword is omitted, it would be created on the stack and when the new keyword is introduced, it would be on the heap.

Edit: I've already visited the links provided when this topic was marked as a duplicate. One user said that when the "new" is omitted, that it couldn't be passed through a method. I was wondering why that was as well. What is the difference between an anonymous array and a regular String array?

Tommy Saechao
  • 991
  • 2
  • 14
  • 24
  • Initialization `new String[] {"one", "two"}` produces [anonymous array](http://stackoverflow.com/questions/1154008/any-way-to-declare-an-array-in-line#comment972671_1154027) that reference to you later assign to `words` variable. Both of them are using [array initializers](https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6), although the latter doesn't have to assign reference to other variable. – Jezor Jul 04 '16 at 00:29
  • There is no difference between these; they're different ways of writing the same thing. That said, Java will only let you use your approach in some very specific cases like the direct variable declaration; you can't pass that in as an array argument directly. – Louis Wasserman Jul 04 '16 at 01:01
  • @LouisWasserman is referring to [this](http://stackoverflow.com/questions/5387643/array-initialization-syntax-when-not-in-a-declaration?lq=1). – Sotirios Delimanolis Jul 04 '16 at 01:28

0 Answers0