mamidi.bunty
mamidi.bunty

Reputation: 39

Java - how to use char array in switch statement?

Can a character array be used in switch statement as shown below? When I tried that, it shows an error that char cannot be converted to int, i.e. incompatible types.

char[] valuetoo = { 'b', 'a', 'c', 'd', 'e'};

switch (valuetoo){
    case 'a':
        System.out.println("the character found is 'a'");
        break;
    case 'b':
        System.out.println("the character found is 'b'");
        break;
    case 'c':
    case 'd':
    case 'e':
        System.out.println("the character found is ");
        break;
    default:
        System.out.println("the characters are not found");
}

The error is:

Error:(39, 16) java: incompatible types: char[] cannot be converted to int

Upvotes: 1

Views: 6262

Answers (3)

Malinda
Malinda

Reputation: 614

You Cannot Pass Array Name to a Switch Case But you can pass Array index to itas below

 switch (valuetoo[0]){
        //body here
        }

Upvotes: 0

Krishna
Krishna

Reputation: 23

You should not use char array inside switch

Better add switch(valuetoo[index])

Upvotes: -2

davidxxx
davidxxx

Reputation: 131456

You provide a char array in the switch clause. You cannot.

The Java language(14.11. The switch Statement) allows only these types as expression of the switch statement:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

You should provide the actual char for which you want to apply the switch-case statement.
Now, if you want to do apply the switch-case statement for all elements of an array of char, you can loop over the switch with the elements of the array :

char[] valuetoo = { 'b', 'a', 'c', 'd', 'e'};      
for (char c : valuetoo){
     switch (c){
        case 'a':
            System.out.println("the character found is 'a'");
            break;
        case 'b':
            System.out.println("the character found is 'b'");
            break;
        case 'c':case 'd':case 'e':
            System.out.println("the character found is ");
            break;
        default:
            System.out.println("the characters are not found");
      }
  }

Upvotes: 3

Related Questions