0

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);
        }

        }

}
1
  • char... is some sweet sugar. Commented Sep 26, 2013 at 20:36

2 Answers 2

3

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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 chars will be converted to passing in an anonymous array, exactly as you did by hand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.