Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.5k points)
edited by
Could someone tell me what does fall-through means in Java?

1 Answer

0 votes
by (11.3k points)

Fall-Through is a specific condition in switch-case conditions, where a case doesn't have a 'break' statement at the end of the case code, and the consecutive cases are prone to execution till a break statement is encountered. I'll elaborate on this by giving you an example of a normal switch case statement where every non-default case HAS a break statement:

  1. int a=1;
  2. switch(a) {
  3. case 1:
  4. a=2
  5. break;
  6. case 2:
  7. a=1
  8. break;
  9. default:
  10. a=a;
  11. break;
  12. }

As we can see here, non-default cases 1 and 2, have a break statement at the end of their code snippets. This means that if a=1, case 1 will be executed and after the execution of the snippet, a break statement will be encountered. This will remove the control from within the switch block and transfer it to the next line of code. The final value of a will be '2' after case 1 executes.

The following is an example of the same code WITHOUT the break statements:

  1. int a=1;
  2. switch(a) {
  3. case 1:
  4. a=2
  5. case 2:
  6. a=1
  7. default:
  8. a=a;
  9. }

As we can see, there are no break statements in this code. The control will go to case 1 upon match first, but after the execution of case 1, the control will then 'fall-through' to case 2, and then to the default case as well. Here, the final value of a will be '1'.

It seems as though you're starting out with JAVA. You can get a better understanding of the basic concepts with some hands-on instructions in this video:

Related questions

0 votes
1 answer
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...