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?
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"});
To pass an array to a constructor we need to pass in the array variable to the constructor while creating an object.
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.
In Java, all array elements are automatically initialized to the default value. For primitive numerical types, that's 0 or 0.0 .
String[] s = {"FOO", "BAR"};
this is allowed at declaration time only
You can't
String[] s; s={"FOO", "BAR"};
Because Type[] x = { ... }
is an initialization syntax for arrays. The { ... }
is interpreted in a specific way only in that specific context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With