Switch – case in Java

Characteristic of the Switch-case

A switch-case statement is used to check the value of a variable with the other values; Each different value is one case. If the case is correct, then the code block of that case will be executed. If all of the cases are wrong, then the default case will be performed. The syntax of Switch-case is:

switch(variable){
    case 1:
        //do something here
    case 2: 
       // do something here
    case n:
       // do something here
    default:
       //do something here
}

The Break statement

The Break command is used to exit the Switch-case block. If the case is correct, then the code of that case will be executed and continue with the following cases (even they are wrong) until seeing the Break command. For example:

public class switchCase{
	public static void main(String[] args){
		int number = 10;
		switch (number){
			case 9:
				System.out.println(number);
			case 10:
				System.out.println(number);
				number = 100;
			case 22:
				System.out.println(number); 
			default:
				System.out.println("end");
		}
	}
}

The output will be:

10
100
end

Now we change a little bit in our code by adding break once executed the code of corrected case:

public class switchCasenơ {
	public static void main(String[] args){
		int number = 10;

		switch (number){
			case 9:
				System.out.println(number);
			case 10:
				System.out.println(number);
				number = 30;
				break;
			case 20:	
				System.out.println(number);
			default:
				System.out.println("end");

		}
	}
}

Now, the output will be

10

Compare to If – else statement

One clear difference between If-else and Switch-case is the condition statement not allowed in Switch-case. It means we have to know precisely the value we want to compare for each case.

case(number < 20): // not allowed
// the case should be specified value, for example
case 5:
    //do something here
    break;

Conclusion

In the case, we know accurately what value will be compared, and there are not so many values, the Switch-case is the right choice.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: