Thursday 26 December 2019

Can I define an array of size 0?


Yes, you can define an array of size 0. 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.

Example
int[] arr1 = {};
int[] arr2 = new int[0];

App.java
package com.sample.app;

public class App {
	public static void main(String args[]) {
		int[] arr1 = {};
		int[] arr2 = new int[0];

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

	}
}

Run App.java, you will see below messages in console.

arr1 length : 0
arr2 length : 0

Reference


You may like

No comments:

Post a Comment