0
class Switch{
    public static void main(String[] args){
        int x = 2;
        switch(x){
            case 1 : System.out.println("1");
            case 2  : System.out.println("2");
            case 3 : System.out.println("3");
            case 4 :System.out.println("4");
        }
    }
}

Why the output will be 2 ,3,4 even if the case 3 and case 4 are not matched with the value of x ?

I know that using break will be printing only 2. But why we have to use break after case 2 as no other cases after it are matching it?

  • 2
    because that's how it is designed. it's a waterfall system. It executes everything until it reaches the end of the switch block, or the first break statement – Stultuske Mar 02 '23 at 06:53

2 Answers2

0

So basically if break is not added, it will execute all the lines, which we do not need.

What we do instead is add 'break', so when the case is true, the logic gets executed, it breaks out of the conditional (switch) and does not execute any other statements. We just want the 'true' case to do its work and rest cases are not of our use.

  • just because it isn't in the same case, doesn't automatically mean you "don't need" them. there's a reason it was implemented as such. For instance: case "2": print(2); case "even": print(even); for the value "2", we would want both, since 2 is an even number – Stultuske Mar 02 '23 at 07:13
  • Yes ofcourse. I meant, if we need it to match just one case and get out, then it is required. Otherwise case dependency is always there. – Gurleen Kaur Mar 02 '23 at 07:58
0

If you do not want it that way, use Java 17 and write:

class Switch
{
  public static void main( String... args )
  {
    final var x = 2;
    switch( x )
    {
      case 1 -> System.out.println( "1" );
      case 2 -> System.out.println( "2" );
      case 3 -> System.out.println( "3" );
      case 4 -> System.out.println( "4" );
      default -> System.out.println( "invalid" );
    }
  }
}

May be it was introduced even earlier than Java 17 …

Alternatively, even this would work now:

class Switch
{
  public static void main( String... args )
  {
    final var x = 2;
    System.out.println( switch( x )
      {
        case 1 -> "1";
        case 2 -> "2";
        case 3 -> "3";
        case 4 -> "4";
        default -> "invalid";
      } );
  }
}

Your version requires the break because it was designed that way in Java, and this was done because C/C++ behave that way, too.

Why the designers of C as the original source for that behaviour did it that way … no idea.

tquadrat
  • 3,033
  • 1
  • 16
  • 29