Java OCAJP7: array initialization

Let’s take a look at this simple snippet that could hide a trap:

public class JavaCertification {
	public static void main(String [] args) {
		int a[] = {1, 2, 3, 4, };
		System.out.println("Number of elements: " + a.length);
	}
}

We see that in the initialization of the array there is an extra comma after the last element, which could make us thinking of a compilation error.
Actually, the code compiles perfectly and produces the following result:

Number of elements: 4

  • There is no compilation error.
  • It does not create a further element initialized with the default value of the type of the array.

This entry was posted in $1$s. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *