Srujan Kumar Gulla
Srujan Kumar Gulla

Reputation: 5841

Array of primitives or objects initialization

Array of String objects can be created as

// Acceptable declarations and initialization

line 1: String[]s = new String[2];
line 2: String[]s = new String[]{"a","b"};

// Below init also looks good to me but compiler errors out

line 3: String[] s = new String[2] { "a", "b" };

1) Why cant i specify the size of the array in line 3?
2) When I create an array using line 3, are strings "a" and "b" created on heap or in String pool?

Upvotes: 0

Views: 78

Answers (2)

Alex Kreutznaer
Alex Kreutznaer

Reputation: 1170

This is done in order to prevent ambiguity.

What should the system do if the number in [] and the actual number of objects you pass doesn't match?

So, the size of your array is defined by the number of object you pass to the initializer.


Second question is a bit incorrect. Java objects are ALWAYS created on the heap.

The String objects in your case are taken from the pool of String objects, because you use literals and compiler can easily realize what their values at run-time will be.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200148

  1. You can't both initialize an array and specify its size, that would just be redundant.

  2. All string literals are stored in the constant pool and that happens before your code runs, at class loading time.

Also note that even new String[] is redundant with an initializer:

String[] s = {"a","b"};

Upvotes: 6

Related Questions