[java] difference between new String[]{} and new String[] in java

I am fresher in java ,i have a doubt in java that is

String array= new String[]{};
  1. what is the use of { } here ?
  2. what is the difference between String array=new String[]; and String array=new String[]{};
  3. when I am writing String array=new String[10]{}; got error why? Help me I am confused.

This question is related to java arrays string

The answer is


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

No difference,these are just different ways of declaring array

String array=new String[10]{}; got error why ?

This is because you can not declare the size of the array in this format.

right way is

String array[]=new String[]{"a","b"};

1.THE USE OF {}:

It initialize the array with the values { }

2.The difference between String array=new String[]; and String array=new String[]{};

String array=new String[]; and String array=new String[]{}; both are invalid statement in java.

It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String

3.String array=new String[10]{}; got error why?

Wrong because you are defining an array of length 10 ([10]), then defining an array of length String[10]{} 0


{} defines the contents of the array, in this case it is empty. These would both have an array of three Strings

String[] array = {"element1","element2","element3"};
String[] array = new String[] {"element1","element2","element3"};

while [] on the expression side (right side of =) of a statement defines the size of an intended array, e.g. this would have an array of 10 locations to place Strings

String[] array = new String[10];

...But...

String array = new String[10]{};  //The line you mentioned above

Was wrong because you are defining an array of length 10 ([10]), then defining an array of length 0 ({}), and trying to set them to the same array reference (array) in one statement. Both cannot be set.

Additionally

The array should be defined as an array of a given type at the start of the statement like String[] array. String array = /* array value*/ is saying, set an array value to a String, not to an array of Strings.


You have a choice, when you create an object array (as opposed to an array of primitives).

One option is to specify a size for the array, in which case it will just contain lots of nulls.

String[] array = new String[10]; // Array of size 10, filled with nulls.

The other option is to specify what will be in the array.

String[] array = new String[] {"Larry", "Curly", "Moe"};  // Array of size 3, filled with stooges.

But you can't mix the two syntaxes. Pick one or the other.


TL;DR

  • An array variable has to be typed T[]
    (note that T can be an arry type itself -> multidimensional arrays)
  • The length of the array must be determined either by:
    • giving it an explicit size
      (can be int constant or int expression, see n below)
    • initializing all the values inside the array
      (length is implicitly calculated from given elements)
  • Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.

Replies

1. String[] array= new String[]{}; what is the use of { } here ?

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

2. what is the diff between String array=new String[]; and String array=new String[]{};

The first 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 not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0]  // size is known, it has 0 elements, explicitly sized

3. when am writing String array=new String[10]{}; got error why ?

(Again, ignoring the missing [] before array) 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.

help me i am confused

Examples

String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2

(Here, "same as" means it will construct the same array.)


Try this one.

  String[] array1= new String[]{};
  System.out.println(array1.length);
  String[] array2= new String[0];
  System.out.println(array2.length);

Note: there is no byte code difference between new String[]{}; and new String[0];

new String[]{} is array initialization with values.

new String[0]; is array declaration(only allocating memory)

new String[10]{}; is not allowed because new String[10]{ may be here 100 values};


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript