Java switch without break

Java Switch Statement Explained [Easy Examples]

A switch statement is a multiple-branch statement in Java. The java switch statement successively checks the value of an expression with a list of integer or character constants. The data type of expression in a switch can be byte, char, short, or int. When a match is found, the statements associated with that constant are executed.

In this tutorial, we will see how we can apply the java switch statement to different data types. Moreover, we will also discuss java switch yield Instruction and Java switch Expression Use Cases.

In a nutshell, this is going to be one of the informative tutorials about java switch statement.

Getting started with Java switch statement

A Java switch statement enables us to select a set of statements to execute based on the value of some variable. This is in effect somewhat similar to the java if statement, although the Java switch statement offers more compressed syntax, and a slightly different behavior than the other java conditional statements. We can apply the java switch statements on various different kinds of data types which we will discuss in a later section.

The general syntax of the java switch statement (without break)

The switch statement evaluates the expression and matches the values against the constant values which are specified in the case statements. When a match is found, the statement associated with that case is executed until it encounters a break statement, or else the switch statement ends. When no match is found, the default statement gets executed. In the absence of a break , the control flow moves to the next case below the matching case and this is called fall through.

The simple syntax of java switch statement without break statement looks like this:

Notice that there is no any break statement so even if we found the best match, the next cases will also be checked. To void this checking after finding the best case, we use break statements.

The general syntax of the java switch statement (with break)

The syntax of java switch with break statements looks like this;

Notice that there is no break statement inside the default block because we don’t actually need a break statement inside it. If you want to put, you can, it will not return any error. It will just take an extra line because anyways the code is going to break/finished after the default case as there are no further cases.

If else vs java switch statements

Java switch works in a similar way to java if-else statements but sometimes using switch statements is much easier and faster than if-else statements. In this section, we will first take an example of an if-else statement and then we will solve the same example using java switch statements as well you can easily see how they are similar to each other.

Читайте также:  Подвал

See the example of an if-else statement below:

// class public class Main < // main method public static void main(String[] args) < int num = 19; // java if else statements if (num==0)< System.out.println("The number is zero"); >else if (num==5) < System.out.println("The number is 5"); >else if (num==15) < System.out.println("The number is 15"); >else < System.out.println("we couldn't find the number"); >> > 
we couldn't find the number

Now let us perform the same action using the java switch statement as well. See the example below:

we couldn't find the number

Notice that we perform the same operation using the switch statement as we did by using if-else statements.

Java switch on different data types

We already had used an example of a java switch statement in the above example which uses a variable. The new version of Java supports this variable to be a byte, short, char, int, and string. You can read more about java bytes from java operator article. In the following sections, take examples of each of these data types with Java switch statements.

Example-1: Java switch on byte

The byte data type is an 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays where the memory savings actually matters.

Let us take an example and see if java supports bytes in switch statements. See the example below.

we couldn't find the number

Notice that the type was byte.

Источник

Java switch case statement

switch-case’ statement can be used as the alternative of ‘if-else-if’ statement where different conditions are defined in different ‘if’ statements. If the first condition returns false, then check the second condition and so on. Defining multiple conditions using this way is a very lengthy process. The same task can be done very simply by using a switch-case statement. It contains different execution parts and executes the statement where the particular value matches with any ‘case’ value. The switch statement can be applied to the various types of primitive data such as int, char, byte, etc. The different uses of switch-case statements in Java are explained in this tutorial.

switch ( variable or expression ) {
case value — 1 :
Statement 1 . N
break ;

case value — 2 :
Statement 1 . N
break ;

case value — n :
Statement 1 . N
break ;

Here, you can use any variable or expression in the switch part that will be matched with the case value. ‘break‘ statement and ‘default’ part are optional for the switch-case statement. But if the ‘break’ statement is omitted for any or all case statements, then the next case value or all case values will be checked with the defined value of the switch part. If none of the case value matches with switch value, then the statements of the default part will be executed. How the switch-case statement works with and without optional parts are shown below by using different examples.

Читайте также:  Питон обращение к элементу массива

Example-1: Use of switch-case statement without break and default

The following example shows how the switch-case statement works when no break and default statements are used. A string data will be taken as input and stored in the variable, ID, and the value of the ID will be checked with each case value. It will not only print the message where the case value match with the ID value but also print all the messages of the remaining case section because no break statement is used. If no case value matches with ID value, then no message will print because no default section is used in the code.

//Import Scanner package
import java.util.Scanner ;

public static void main ( String [ ] args ) {

// Create a Scanner object
Scanner input = new Scanner ( System . in ) ;

System . out . print ( «Enter your ID: » ) ;
// Take string data from the user
String ID = input. next ( ) ;

//Switch expression
switch ( ID ) {

//Case statement-1
case «0111786» :
System . out . println ( «Your batch is 24» ) ;

//Case statement-2
case «0111234» :
System . out . println ( «Your batch is 20» ) ;

//Case statement-3
case «0111923» :
System . out . println ( «Your batch is 37» ) ;

}
//Close the scanner object
input. close ( ) ;

The following output will appear if the input value matches the first case value after executing the script. The last two messages are printed here for omitting the break statement.

When the input value matches the second case value, then the following output will appear.

When the input value does not match with any case value, then no output will appear for the omitting default section.

Example-2: Use of switch-case statement with default section

The default section is essential for a switch-case block to print a message for the user that no match is found. The following example shows the use of the default section in the switch-case block. Here, the value of the number will be checked with each case value of the switch-case statement, and no match is found, then the message of the default section will be printed.

public static void main ( String [ ] args ) {

int number = 380 ;
switch ( number ) {

//Case statement-1
case 440 :
System . out . println ( «You are selected for group A» ) ;

//Case statement-2
case 500 :
System . out . println ( «You are selected for group B» ) ;

Читайте также:  Java печать массива чисел

//Case statement-3
case 890 :
System . out . println ( «You are selected for group C» ) ;

//Execute default statement if all case returns false
default :
System . out . println ( «Sorry, you are not selected» ) ;
}

The following output will appear after executing the code. According to the code, the value assigned in the number variable does not match any case value. So, the message of the default section is printed here.

Example-3: Use of switch-case statement with default and break

The following example shows the use of a switch-case statement with the default section and breaks statement. Here, the course code will be taken as input from the user, and that will be checked with each case value. If any match exists, then the statements of the matching case section will be executed, and the program will terminate from the switch-case block for using a break statement. If no match exists, then the statements of the default section will be executed.

//Import Scanner package
import java.util.Scanner ;

public static void main ( String [ ] args ) {
// Create an Scanner object
Scanner input = new Scanner ( System . in ) ;

System . out . print ( «Enter the course code: » ) ;
// Take string data from the user
String code = input. next ( ) ;

//Case statement-1
case «CSE-105» :
System . out . println ( «Course Name: Java Programming» ) ;
System . out . println ( «Credit hour: 2» ) ;
System . out . println ( «Semester: 2» ) ;
break ;

//Case statement-2
case «CSE-207» :
System . out . println ( «Course Name: Data Structure» ) ;
System . out . println ( «Credit hour: 2» ) ;
System . out . println ( «Semester: 4» ) ;
break ;

//Case statement-3
case «CSE-402» :
System . out . println ( «Course Name: Artificial Intelligence» ) ;
System . out . println ( «Credit hour: 3» ) ;
System . out . println ( «Semester: 10» ) ;
break ;

//Execute default statement if all case returns false
default :
System . out . println ( «Invalid course code» ) ;
}

//Close the scanner object
input. close ( ) ;

After executing the code, it will ask for the course code from the user. Here, CSE-105 is taken as input that matches with the first case value. So, the details of the course information are printed, and other case sections are omitted for using a break statement.

Next, CSE-402 is taken as input that matches the last case value, and the corresponding course details are printed.

Next, CSE-101 is taken as input that does not match with any case value, and the message of the default section is printed.

Conclusion:

Using a switch-case statement is efficient in many cases instead of using the if-else-if statement for solving particular problems. The concept and the use of the switch-case statement are appropriately explained in this tutorial to help Java users to apply it efficiently in their code based on the requirement.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Оцените статью