-4

Hi is it possible to use a string in a switch statement or does it require a numeric value. For example,

Switch (legs){case "Nice:" return "A nice person"}

Is this executable code?

jazzurro
  • 23,179
  • 35
  • 66
  • 76
extraginger
  • 1
  • 1
  • 1

2 Answers2

4

It is possible starting in Java 7: http://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html

cybersam
  • 63,203
  • 6
  • 53
  • 76
1

Yes. In Java 7 and up, but your syntax is a little off. Something like this,

String legs = "Nice:";
switch (legs) {
case "Nice:":
    System.out.println("A nice person");
    break;
default:
    System.out.println("Not a nice person");
    break;
}

Output is

A nice person
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249