Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This question is listed with a Java tag so...</p> <p>Generic switch statement:</p> <pre><code>// ... within class scope private final int CONSTANT_1 = 1; private final int CONSTANT_2 = 2; private final int CONSTANT_3 = 3; // ... public void doStuff(MyObject myObject){ int variable = myObject.getIntValue(); switch(variable){ case CONSTANT_1: System.out.println(variable + " is equal to " + CONSTANT_1); // use a break statement to tell the switch to stop here // or else it will execute all subsequent cases: break; case CONSTANT_2: System.out.println(variable + " is equal to " + CONSTANT_2); // what happens if I leave out the break? case CONSTANT_3: System.out.println(variable + " is equal to " + CONSTANT_2); break; default: System.out.println(variable + " wasn't equal to anything!"); } </code></pre> <p>Let's say I run through this 3 times and "myObject.getIntValue()" returns these values in this order; 3, 1, 2, and finally 42. Then the following output would be generated: First time through using the value '3'...</p> <blockquote> <p>3 is equal to 3</p> </blockquote> <p>Second time through using the value '1'...</p> <blockquote> <p>1 is equal to 1</p> </blockquote> <p>Third time through using the value '2'...</p> <pre>2 is equal to 2 2 is equal to 3</pre> <p>Fourth time through using the value '42' ...</p> <blockquote> <p>42 wasn't equal to anything!</p> </blockquote> <p>Notice the third run has two lines (and one incorrect one) because I left out the break keyword for the second case.</p> <p>Now in Java 1.5 and up, you can also switch on the Enum type:</p> <pre><code>public void doStuff(MyObject myObject){ MyEnumType varType = myObject.getEnum(); switch(varType){ case MyTypeOne: // everything else is the same -- nothing special here. // put whatever code you want in. break; case MyTypeTwo: // everything else is the same -- nothing special here. // put whatever code you want in. break; case MyTypeThree: // everything else is the same -- nothing special here. // put whatever code you want in. break; default: // code for unknown case goes here } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload