-1

I am trying to use message==null and message!=null with switch case , but it gives me syntax error . Here is the code

    String message = "Happy New Year ;)";
switch (message) {
case null :
    break;
case !null :
    System.out.println(message);
    break;
    default :           
}

I've done it with if{}else{} and it has no problem with it , but I don't know what is wrong with switchCase .

   if(message == null) {
     
 }else if (message != null) {
     System.out.println(message);
 }

Thank you for your response ❤

2 Answers2

3

Java doesn't support using null in switch statements

Null in switch case Java Java docs clearly stated that: The prohibition against using null as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, such as a boxed primitive type or an enum, a run-time error will occur if the expression evaluates to null at run-time

1

You cannot do !null in java since null is not of type boolean.

Instead, try checking for it before since you know you will not have entered the else clause if message was null.

String message = "Happy New Year ;)";
if (message == null) {
  // error
}
else {
  switch (message) {
    case x:
      y();
      break;
    default:
      System.out.println(message);
      break;
  }
}
Coder
  • 1,175
  • 1
  • 12
  • 32