string initialization

By | July 19, 2019

In this article, you will find types of string array initialization.

1. what is the use of { } in below statement?

String[] array= new String[]{};

Ans: Here it initializes the string array with the values between { }. In this case zero elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException.

2. What is the difference between

String array=new String[]; and String array=new String[]{};

The first one won’t compile for two reasons while the second won’t compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:

new String[] // size unknown, compile error
new String[]{} // size is known but it has zero elements, listed inside {}
new String[0] // size is known, it has zero elements, explicitly sized.

3. When writing String array=new String[10]{}; Will get error. Why ?

In this case you’re over-eager to tell Java what to do and you’re giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you’re saying you want the array to be empty via {}. Just make up your mind and use one of those – Java thinks.

 

Must reads:

Hashset and Linked Hashset differences.

How to convert String to int in Java.

Leave a Reply

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