Java Switch Statement

I have a problem using switch statement when I tried to deal with a special situation. For example, I have 3 cases: A, B, C.

  • for A, I want to do statement_1 and statement_3.
  • for B, I want to do statement_2 and statement_3.
  • for C, I want to do nothing

if I use if-else statement, it will look like the following:

 if ( not C){
    do statement_3

   if B
      do statement 2
   else if A
      do statement 1

 }

If I want to use switch statement to do the same thing, I have some trouble.

switch (variable){
case A:  do statement_1
case B: do statement_2
// how to do statement 3 here?  
}

I am trying to avoid the duplicated codes. So I am thinking that how to make the codes as simple as I can.

UPDATE 1:

  1. to make my codes/question more clear, I just want to make my codes as simple/clear as I can, that is why I want to use switch statement instead of if-else. Also, I heard that switch-statement is usually faster than if-else. (I am not 100% sure though).

  2. I want to use switch-case because Case A, B, C are enum type. they are not variable. Sorry about the confusion.

  3. each statements are more than 10 lines of codes. That is why I do not want to do the followings:

    switch (enum variable) {
    case A:
      statement1
      statement3
     break;
    case B:
      statement2
      statement3
     break;
    

    }

Answer

i would recommend to define exactly what staments should be executed:

switch (variable){
    case A: 
        statement_1();
        statement_3();
        break;
    case B: 
        statement_2();
        statement_3();
        break;
}

for Update-3:

create methods for those 10 lines:

public void statement_1() {
    //your 10 lines of code
}

if you’re always executing statement_3, except for case C you can go with if/else-blocks as you wrote them.

but in my honest opinion: define EXACTLY what has to be done in which case if you have a small amount of cases. it is easier to read for others

Leave a Reply

Your email address will not be published. Required fields are marked *