Java Switch Statement with Programming Examples
Java Switch Statement:
Java Switch Statement:- Java provides an alternative to case discrimination nested if-else constructions to the switch construction. The expression is passed to switch – a number, a Boolean value, an enum object, or string. Subsequently, the code of all case blocks from the first applicable Constant. break terminates the entire switch construction. The optional default block is provided for the case that no case constant applies. For the statements after case or default, no curved brackets are required. Clarify the syntax of the following line:
syntax of Java switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
switch ( expression ) { case constant1: instruction1a ; instruction1b ; break; case constant2: instruction2a ; instruction2b ; break; default: statement3a ; statement3b ; } |
The constants introduced with the word symbol case with the following Colons define entry marks for the program sequence. Between two such entry marks do not necessarily have to contain instructions. There are also the abort statements (break;) and the label default: and the following statements optional. In principle, the statements in the switch block are a sequence of instructions, some of which are marked as entry points. Here namely, the expression is evaluated first, the result type of which is a byte, must be short, int or char. The program sequence will then be exactly the case label, which contains the result of the expression as a constant, until a break statement is encountered, via which the java switch Statement terminated immediately. If the result of the expression is not in any case If an instruction is found, then the program is executed with the instructions continued after the default mark. It should be noted that not only each by a case mark marked instructions are executed, but that with the execution all subsequent statements are continued and only the next break Statement aborts the execution of the entire java switch statement and the Program flow with the first statement outside the switch statement continues. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
int a, b; switch (a) { case 1: b = 10; case 2: case 3: b = 20; break; case 4: b = 30; break; default: b = 40; |
In this java switch statement, the value 20 is assigned to the variable b, if a is 1, 2, or 3. Why? If a has the value 1, then at first becomes the first case mark jumped and the value 10 assigned to the variable b. After that, however, processing continues with the next statement, since not with a break statement explicitly to leave the entire switch Instruction was prompted. After the second case mark there is no Command executed and processing continues with the instruction after the third case brand. Now variable b is assigned the value 20 and then leave the entire java switch statement with a break statement.
If a contains the value 4 at the beginning of the java switch statement, then b becomes the value 30, in all other cases b contains after the execution of the java switch statement finally has the value 40. There is no expression for a switch statement at runtime a suitable case mark and no default mark, so the whole remains switch statement for the program flow has no effect (such as an empty Statement, only the execution of the java switch statement takes more time Claim).
Note:
Don’t forget to break.
Without break, all statements from the first applicable case Printed to the end of the switch construction. Dignity in the above listing, the break expressions are missing and would be expression1 == constant1, if Java were to use statements 1a, 1b, 2a, 2b, 3a and 3b. This is rarely intended. Forget about so do not specify a break at the end of each case block!
Java does not offer the possibility of multiple constants or constant ranges in a case statement. However, in several cases Place instructions in a row. Follow the instructions until the next break then apply to all the constants listed above.
For example: how to find Days per month using the java switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public class demo { public static void main (String [] args) { String month="March"; int days =0; switch(month) { case "January": case "March": case "May": case "July": case " August ": case " October ": case " December ": days = 31; break; case "April": case "June": case " September ": case " November ": days = 30; break; case "February": days = 28; // or 29, if leap year break; default: System.out.println ("Invalid month name!"); days = 0; } if (days !=0) { System.out.println ("The " + month + " has " + days + " days ."); } } } |
output:
Example: how to use java switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.Scanner; public class demo {public static void main (String [] args) { int n; System.out.print ("give an integer:"); Scanner scan= new Scanner(System.in); n = scan.nextInt(); switch (n) {case 0: System.out.println ("null"); break; case 1: System.out.println ("one"); break; case 3: System.out.println ("three"); break; } System.out.println (" Goodbye "); } } |
Output:
The java switch statement here spans eight lines (it begins at the word switch). Its execution proceeds as follows. We start by evaluating the expression appearing after the word switch (here n). Then we search in the following block if there is a label of the form case x corresponding to the value thus obtained. If this is the case, we connect to the instruction appearing after this label. Otherwise, we go to the instruction following the block. For example, when n is 0, we actually find a case 0 label and we execute the corresponding instruction, i.e :
System.out.println (“null”);
We then go naturally to the next instruction, namely here:
break;
This actually asks to get out of the block. Note that the role of this instruction is fundamental. See, as an example, what this same program would produce in the absence of instructions break:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Scanner; public class demo {public static void main (String [] args) { int n; System.out.print ("give an integer:"); Scanner scan= new Scanner(System.in); n = scan.nextInt(); switch (n) { case 0: System.out.println ("null"); case 1: System.out.println ("one"); case 3: System.out.println ("three"); } System.out.println (" Goodbye "); } } |
output:
The default label:
It is possible to use the default keyword as the label to which the program will plug if no satisfactory value has been encountered before. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Scanner; public class demo {public static void main (String [] args) { int n; System.out.print ("give an integer:"); Scanner scan= new Scanner(System.in); n = scan.nextInt(); switch (n) { case 0: System.out.println ("null"); break; case 1: System.out.println ("one"); break; default: System.out.println ("large"); } System.out.println (" Goodbye "); } } |
output:
Likewise, since an integer constant expression is compatible with types byte, char and short, this construction is correct:
1 2 3 4 5 6 7 8 9 10 11 12 |
char c; ..... switch (c) { case 48: ..... case ’a’: ..... } |
Finally, since the syntax of the switch allows not only constants but also constant expressions, the following example is correct:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
final int LIMIT = 20; switch (n) { case LIMIT - 1: ..... case LIMIT : ..... case LIMIT + 1: ..... } |
After compilation, the expressions LIMITE-1, LIMITE, and LIMITE + 1 will actually be replaced by the values 19, 20, and 21.
Nested Switch case statements in Java:
We can utilize a switch as a feature of the statement sequence of an external switch. This is known as a nested switch. Since a switch statement characterizes its own block, no contentions emerge between the case constants in the internal switch and those in the external switch. For example:
Example: how to find subjects by putting branch and year using java nested switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import java.util.Scanner; public class demo{ public static void main(String args[]) { char branch; int collegeYear; Scanner input = new Scanner(System.in); System.out.print("Enter branch: "); branch= input.next().charAt(0); System.out.print("Enter year: "); collegeYear= input.nextInt(); switch( collegeYear ) { case 1: System.out.println("English, Maths, Urdu,Pushto"); break; case 2: switch( branch ) { case 'c': System.out.println("Operating System, Java, Data Structure"); break; case 'e': System.out.println("Micro processors, Logic switching theory"); break; case 'm': System.out.println("Drawing, Manufacturing Machines"); break; } break; case 3: switch( branch ) { case 'c': System.out.println("Computer Organization, MultiMedia"); break; case 'e': System.out.println("Fundamentals of Logic Design, Microelectronics"); break; case 'm': System.out.println("Internal Combustion Engines, Mechanical Vibration"); break; } break; case 4: switch( branch ) { case 'c': System.out.println("Data Communication and Networks, MultiMedia"); break; case 'e': System.out.println("Embedded System, Image Processing"); break; case 'm': System.out.println("Production Technology, Thermal Engineering"); break; } break; } } } |
output:
Program Examples of Java Switch Statement:
Example: how to make Calculator using Java switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import java.util.Scanner; class demo{ public static void main(String[] args) { char op; Double value1, value2, result; Scanner input = new Scanner(System.in); System.out.print("Choose an operator: +, -, *, or /: "); op = input.next().charAt(0); System.out.print("Enter first value: "); value1 = input.nextDouble(); System.out.print("Enter second value: "); value2 = input.nextDouble(); switch (op) { // performs addition between numbers case '+': result = value1 + value2; System.out.print(value1 + "+" + value2 + " = " + result); break; // performs subtraction between numbers case '-': result = value1 - value2; System.out.print(value1 + "-" + value2 + " = " + result); break; // performs multiplication between numbers case '*': result = value1 * value2; System.out.print(value1 + "*" + value2 + " = " + result); break; // performs division between numbers case '/': result = value1 / value2; System.out.print(value1 + "/" + value2 + " = " + result); break; default: System.out.println("Invalid operator!"); break; } input.close(); } } |
output:
Example: how to find the month name by putting the month number using java switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import java.util.Scanner; class demo{ public static void main(String[] args) { int month; String monthString=""; Scanner input = new Scanner(System.in); //Specifying month number System.out.print("Enter Month: "); month = input.nextInt(); //Switch statement switch(month){ //case statements within the switch block case 1: monthString="1 - January"; break; case 2: monthString="2 - February"; break; case 3: monthString="3 - March"; break; case 4: monthString="4 - April"; break; case 5: monthString="5 - May"; break; case 6: monthString="6 - June"; break; case 7: monthString="7 - July"; break; case 8: monthString="8 - August"; break; case 9: monthString="9 - September"; break; case 10: monthString="10 - October"; break; case 11: monthString="11 - November"; break; case 12: monthString="12 - December"; break; default:System.out.println("Invalid Month!"); } //Printing month of the given number System.out.println(monthString); } } |
output:
Enter character to find whether it is a Vowel or Consonant:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import java.util.Scanner; class demo{ public static void main(String[] args) { char vowel; Scanner input = new Scanner(System.in); //Specifying character System.out.print("Enter character to find whether it is a vowel or Consonant: "); vowel = input.next().charAt(0); //Switch statement switch(vowel) { case 'a': System.out.println("Vowel"); break; case 'e': System.out.println("Vowel"); break; case 'i': System.out.println("Vowel"); break; case 'o': System.out.println("Vowel"); break; case 'u': System.out.println("Vowel"); break; case 'A': System.out.println("Vowel"); break; case 'E': System.out.println("Vowel"); break; case 'I': System.out.println("Vowel"); break; case 'O': System.out.println("Vowel"); break; case 'U': System.out.println("Vowel"); break; default: System.out.println("Consonant"); } } } |
Example: how to use wrapper class in a Java switch statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.Scanner; public class demo{ public static void main(String args[]) { Integer age; Scanner input = new Scanner(System.in); System.out.print("Enter Age: "); age = input.nextInt(); switch (age) { case (16): System.out.println("You are under 18 not eligible for vote."); break; case (18): System.out.println(" eligible for vote."); break; case (65): System.out.println("You are senior citizen."); break; default: System.out.println("Please give the valid age."); break; } } } |
output:
Related Articles:
Java if Statement: if else, correct indentation, ternary operator, nested if
Operators in java: Arithmetic, Bit, Assignment, Comparison, Logical And Operators Priority