Reputation: 20856
I'm creating anonymous array and passing it to a method which is declared to receive a variable argument character...
I'm wondering how the below code will run successfully, I'm passing a array of characters {'A','B','C,'D'} and the method can receive only characters...shouldn't it fail with wrong types passed? ie; character array vs characters?
public class test {
public static void main(String[] args) {
callme(new char[]{'A','B','C','D'});
}
static void callme(char... c){
for (char ch:c){
System.out.println(ch);
}
}
}
Upvotes: 0
Views: 61
Reputation: 533492
They are the same. A char...
is a char[]
You can also write
public static void main(String[] args) {
callme('A','B','C','D');
}
static void callme(char... c){
for (char ch : c) {
System.out.println(ch);
}
Upvotes: 3
Reputation: 198033
This will work fine. All the varargs syntax with char...
actually does is that it is actually implemented as callme(char[] c)
, and all the callers of that method who just pass in comma-separated char
s will be converted to passing in an anonymous array, exactly as you did by hand.
Upvotes: 1