Monday, January 9, 2023

java switch statement | Java Tutorial For Beginners

 Switch statement is alternative and more cleaner way to write code if we have more than two options. we can use else if, this is better way. So lets start learning. 

If you want to watch video tutorial for how to use switch statement in java simple click on below tutorial link. 

Java Tutorial Switch Statement in Hindi



For illustration purpose we will use school grade example . we will male program if student get grade A we will print wow great job, if student get grade B we will print good job, if user get grade c we will print you passed, if user get grade f we will print , you failed and for any other grade we will print sorry you not appear . So lets get started. 
First we will declare variable grade, datatype as char. 
After that we will type switch and in the parenthesis we will pass our grade.  and we will add curly brace. Now we will type case A  and will print great job, and add break. It means in the grade if user get A grade then  we will print this statement. Now we will add case B and we will print good job . and we will type break . Now we will repeat for grade C.  Repeat process for grade F and add print statement. now at last we will add default it means any thing which is not mentioned in case , will fall in default and run that block of  code. 
Now in the grade variable assign A as grade and run program. In the result it will run block of Case A similarly try different Cases and check result. 
Switch Statement Java example. 

char grade = 'A';
switch(grade){
case 'A':
System.out.println("Wow great job");
break;
case 'B':
System.out.println("Good Job job");
break;
case 'C':
System.out.println("You Passed ");
break;
case 'F':
System.out.println("You Failed ");
break;
default:
System.out.println("You have not appear... ");

java switch statement | Java Tutorial For Beginners

 Switch statement is alternative and more cleaner way to write code if we have more than two options. we can use else if, this is better way...