Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Enjoy Java with SWITCH Statement !!!

Tags: write

public class DoSwitch {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int dj =7;

switch(dj)
{
case 1: System.out.println("David Guetta");
break;

case 2: System.out.println("Tiesto");
break;

case 3:
case 4:
case 5: System.out.println("Deadmau5");
break;

case 6: System.out.println("kaskade");
break;

default : System.out.println("U must listen all dj before u select !");

}
}

}
______________________________________________

Output:

U must listen all dj before u select !

_____________________________________________

In this program, we are using "switch statement" to select from different case. Just declare the variable you want in your code and put it beside switch. In switch statement, we have to write case word to make it different from each case and also give them numbers so whenever we enter that number than we can call particular result which is there in particular number. This is small example of big program where we have to select from many option.

In the above code, you can see that "break" word which really help to break the rest of the option. Just try to remove all "break" and you can see if you select number 1 than all other option will be printed in output. If you put break than that case break itself and it will be ignore other options.

Now as you can see that I write "case 3 and 4" empty, this mean what ever I write in "case 5" mean result in "case 3 and 4". Here "case 5" is "Deadmau5" and so if you write number 3 than still it show you same result that is Deadmau5.

You might be surprise that why we write default, because if you write the option that is not exist in this program than it will show that message. In this program, if you write any number than 1 to 7 than it show you default message.

Thank you for your time.................


This post first appeared on LET's START CORE JAVA !, please read the originial post: here

Share the post

Enjoy Java with SWITCH Statement !!!

×

Subscribe to Let's Start Core Java !

Get updates delivered right to your inbox!

Thank you for your subscription

×