Thursday 26 December 2019

Can I define an array with negative size?

No, you can’t define an array with negative size. As per Java documentation, array has public final field length, which contains the number of components of the array. length may be positive or zero.

App.java
package com.sample.app;

public class App {
	public static void main(String args[]) {
		int[] arr1 = new int[-1];

		System.out.println("arr1 length : " + arr1.length);

	}
}

Run App.java, you will get ‘NegativeArraySizeException’.

Exception in thread "main" java.lang.NegativeArraySizeException
         at com.sample.app.App.main(App.java:5)

Reference



You may like

No comments:

Post a Comment