user1971598
user1971598

Reputation:

Need clarification for java array declaration

If we do int[] b = {2, 4}; then we have an array called b, with length 2. From what I understand, the java compiler is implicity doing int[] b = new int[] {2, 4}; for me, fine.

Similarly, if we do int[] c = new int[2]; , then we get an array called c initialzed to {0, 0} My confusion comes from why the following doesn't work:

Why can't I do int[] d = new int[2] {5, 6};

Upvotes: 0

Views: 52

Answers (1)

Robbie
Robbie

Reputation: 101

It's just a compiler thing. Besides, why would you want to manually input the size anyway? This will just be a source of error.

The int[] b = new int[] {2, 4} notation is for convenience, if you already know the contents of the array that you want to declare.

Upvotes: 3

Related Questions