2

I just found a random code snippet:

int[] i = new int[]{0,};

How is this even possible?

Primitive types can't be null...

I just wonder what this is creating...

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
RoiEX
  • 1,186
  • 1
  • 10
  • 37

2 Answers2

2

Here new int[] will create an array and initialize with array elements {1}.

new int[]{1,}; // Create an array of int of size 1 with value 1 as a first element

if you print the length of int[] i. Size will be print 1. because last comma is ignored if no further element found.

System.out.println(i.length); // it will print 1 

Here i is a reference variable which holds the array Onject. while new int[] will only responsible for creating Array.

Thank You

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
2

This would create an array of length 1 which is equivalent to

int[] i = new int[]{0};

The last comma will be ignored as specified in JLS §10.6

A trailing comma may appear after the last expression in an array initializer and is ignored.

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77