A String array can be declared and initialized in the following way:
String[] str = {"A", "B"};
but for a method which accepts a String array as argument, why can't the same be used there?
For example: if in the code below, i replace the call to show() from show(str);
to show({"A" "B"});
, it shows complier error. Why?
public class StringArray {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] str = {"A", "B"};
show(str);
}
static void show(String[] s) {
System.out.println(s[0] + s[1]);
}
}
The compiler errors shown are:
StringArray.java:9: illegal start of expression
show({"A", "B"});
^
StringArray.java:9: ';' expected
show({"A", "B"});
^
StringArray.java:9: illegal start of expression
show({"A", "B"});
^
StringArray.java:9: ';' expected
show({"A", "B"});
^
StringArray.java:9: illegal start of type
show({"A", "B"});
^
StringArray.java:11: class, interface, or enum expected
static void show(String[] s) {
^
StringArray.java:13: class, interface, or enum expected
}
^
7 errors
Also using show(new String[] {"A", "B"});
is allowed. How is new String[]{"A", "B"}
different from {"A", "B"}
when passing them as method arguments?
Thanx in advance!
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
Passing Array To The Method In Java To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type. Given below is the method prototype: void method_name (int [] array);
Because by passing String arrays , we can pass all the necessary parameters like options/arguments related to the program in the form of String easily. There can be several parameters! Also, all the other datatypes can be easily converted from String!
The syntax {"A", "B"}
(without new String[]
in front of it) can only be used as an array initializer expression. In all other contexts (including method calls), you need to use the new
operator.
See the Java Tutorial on Arrays for more info.
String[] str = {"A", "B"};
is minified version of String[] str = new String[]{"A", "B"};
, Compiler doesn't know about plain {"A", "B"}
as a string array unless you explicitly mention.
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