Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String array initialization as constructor parameter [duplicate]

In Java, it is completely legal to initialize a String array in the following way:

String[] s = {"FOO", "BAR"}; 

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

Test t = new Test({"test"}); 

But this works again:

Test t = new Test(new String[] {"test"}); 

Can someone explain why this is?

like image 733
Hermann Hans Avatar asked Dec 14 '10 06:12

Hermann Hans


People also ask

How do you initialize a string array constructor in Java?

In Java, it is completely legal to initialize a String array in the following way: String[] s = {"FOO", "BAR"}; However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed: Test t = new Test({"test"});

Can we pass array in constructor in Java?

To pass an array to a constructor we need to pass in the array variable to the constructor while creating an object.

How do you pass an array to a constructor in C++?

In c++ , the name of the array is a pointer to the first element in the array. So when you do *state = *arr , you store the value at arr[0] in the variable state. Show activity on this post. The name of an array is the address of the first element in it.

Does Java automatically initialize arrays?

In Java, all array elements are automatically initialized to the default value. For primitive numerical types, that's 0 or 0.0 .


2 Answers

String[] s = {"FOO", "BAR"};   

this is allowed at declaration time only

You can't

String[] s; s={"FOO", "BAR"};   
like image 112
jmj Avatar answered Oct 04 '22 21:10

jmj


Because Type[] x = { ... } is an initialization syntax for arrays. The { ... } is interpreted in a specific way only in that specific context.

like image 33
Karl Knechtel Avatar answered Oct 04 '22 22:10

Karl Knechtel