If-Else v/s switch statements in Java
![]() |
Image Source - Google | Image by - codeamy |
let's try to understand what are if-Else and switch statements in Java and why we need to use it in our program basically when you want to give some condition to the user that when this specified condition is true our program do this and when this particular condition is true our program do this otherwise when neither the first condition and second condition holds good our program do this for example if you are writing a program of showing different brands of laptop according to the user input (user will give the brand name and according to the brand name laptop appears on the screen) if user give HP as an input various hp laptops will appear, similarly for DELL, MICROSOFT and APPLE and if user is little smart and write something different which is not a brand name of laptop what will be shown to the user these all cases will be handled by the programmer with the help of IF-ELSE and SWITCH statements the coder's motive is the program should not terminate and spoil the user experience in any case it should response according to the programmer in every possible condition so we use IF-ELSE statements and SWITCH statements in java in order to give the best user experience in every required case because it is supposed that programmer writes the code by keeping all the things in mind what the end user is thinking while using the application so without any more theory let's see directly in the code how they are implemented in java-
Syntax of if-else statement is given below:
//
syntax of IF- ELSE statements
public static void main(String[] args) { if(condition) { //statements; }//
you can have multiple if statements
else if(another condition) { //statements; } else if(another condition) { //statements; }//
you can have multiple else if statements
else //
no condition will be given here if none of the condition is true it will execute automatically
{ //statements; } //
you will have only one else statement
}
program 1- "Eligible to vote or not" according to the age using IF-ELSE statements -
problem statement- User will be asked enter your age if his/her age < 18 show he/she is not eligible to vote is shown to the user and for age>18 show he/she is eligible to vote is shown to the user have a look on the code.
import java.util.Scanner;
public class IfClass {
public static void main(String[] args) {
int age = 0;
Scanner sc = new Scanner(System.in);//method to take user input
age = sc.nextInt();
if(age >=1 && age <=5 )//condition-1
{
System.out.println("you are a child "+"\n"+"obviously not eligible to vote"+"\n"+"go and have some fun");
}
if(age >=6 && age <=17)//condition-2
{
System.out.println("you are not eligible to vote");
}
else if(age >=18)//condition-3
{
System.out.println("you are eligible to vote");
}
else//It executes when none of the condition holds true
{
System.out.println("enter a valid value");
}
}
}
Syntax of switch statement is given below:
public static void main(String[] args) { switch(variable/expression) { case variable value://condition-1 //statements; break; case variable value://condition-2 //statements; break; case variable value://condition-3 //statements; break; default: //when no case matches with your value it will execute automatically //no need to use break here }
}
program 2- "Eligible to vote or not" according to the age using switch statement -
public static void main(String[] args) {
int age=0;
switch(age) {
case 4:
System.out.println("you are a child "+"\n"+"obviously not eligible to vote"+"\n"+"go and have some fun");
break;
case 6:
System.out.println("you are not eligible to vote");
break;
case 21:
System.out.println("you are eligible to vote");
break;
//In this switch statement you have to give all ages which are eligible to vote so it is not preferred in this age problem
//let's see another switch case problem where it will be used
default:
System.out.println("enter a valid value");
}
}
}
program 3- "Schedule of a week according to the day of week " using switch statement-
problem statement- User will be asked to enter the day of week in number like 5, 4, 2, 6 out of 7 including 7 obviously and it will shown to the user what you have to do on this day hope it is clear to you have a look on the code.
public class SwitchCaseStatements { public static void main(String[] args) { int dayOfWeek; switch(dayOfWeek) { case 1:
//value of dayOfWeek variable
System.out.println("you have to code all the day"); break; case 2:
//value of dayOfWeek variable
System.out.println("you will play pubg today"); break; case 3:
//value of dayOfWeek variable
System.out.println("you will play basketball today"); break; case 4:
//value of dayOfWeek variable
System.out.println("you will work on your side project today"); break; case 5:
//value of dayOfWeek variable
System.out.println("you have to go on a hill station today"); break; case 6:
//value of dayOfWeek variable
System.out.println("you have to spend time with your family today"); break; case 7:
//value of dayOfWeek variable
System.out.println("spend time with your girlfriend today"); break; default: System.out.println("please enter a valid value"); } }
Important points to remember-
- It is necessary to use break keyword after every case except for default because if you will not use break keyword after a particular case all case will be executed from the current case till default case.
- You will use Switch statement where there is a limit to the number of cases as you have seen above in case of age problem when age>18 how you will proceed for all the ages>18 you have to write for every possible case so when there is no limit to the number of cases you can go with the if else statements simply.
Differences between switch and if else statements-
- You can use only integer and character and strings to evaluate in switch statement.
- But you can evaluate integer, floating point, character, pointer, or a boolean in if else statements
- In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based on the condition.
- In the case of the 'switch' statement, one case after another will be executed until the break keyword is not found, or the default statement is executed.
- If the condition is not true within the 'if' statement, then by default, the 'else' block statements will be executed.
- If the expression specified within the switch statement is not matched with any of the cases, then the default statement, if defined, will be executed.
what are Nested If-Else statements..?
If you want to satisfy some condition inside another condition or wants to use if else statement inside another if-else statement you can go with nested if-else statements in java simply you can use multiple if-else statements inside one another this is called nested if-else, to better understand this have a look on the syntax of nested if-else statements-
if(condition)
{
//outer if statement code according to you
if(condition)
{
//inner if statement code according to you
}
}
if(condition)
{
//outer if statement code according to you
if(condition)
{
//inner if statement code according to you
}
}
program 4- "To check the maximum of three numbers" by using nested if-else statements-
problem statement- User will be asked to enter three numbers one by one and output will show the maximum of three numbers entered by the user, user can enter any three numbers according to his/her choice.
import java.util.Scanner; public class MaxOfThree2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("enter any number "); int n1 = sc.nextInt(); System.out.println("enter second number "); int n2 = sc.nextInt(); System.out.println("enter third number "); int n3 = sc.nextInt(); if(n1>n2) { if(n1>n3) { System.out.println(n1+"is the largest number"); } else if(n3>n1) { System.out.println(n3+"is the largest number"); } else if(n2==n3) { System.out.println(n1+"is the largest number"); } } else if(n2>n1) { if(n2>n3) { System.out.println(n2+"is the largest number"); } else if(n3>n2) { System.out.println(n3+"is the largest number"); } else if(n2==n3) { System.out.println(n2+"is the largest number"); } } else if(n1==n2) { if(n1>n3) { System.out.println(n1+"is the largest number"); } else if(n3>n1) { System.out.println(n3+"is the largest number"); } else if(n1==n3) { System.out.println("all are equal"); } } }
}
what are jump statements(break and continue) in java..?
break: It is basically a loop control statement in java that is used to terminate a loop when it is encountered the control immediately transfers out of the loop and go to the first statement after the loop. It can be used in loop and switch case only let's see how it works in loop and switch case one by one-
In loop-
public class Myloop {
//show numbers from one to five in a 1 to 10 loop
public static void main(String[] args) {
for(int i=1;i<=10;i++)
{
if(i==6)
{
break;
}
else
{
System.out.println(i+"\n");
}
}
}
}
In switch- In order to terminate the specific case in switch after complete execution of it we simply use break keyword let's see this with a switch case example using break-
public class Myloop {
//show numbers from one to five in a 1 to 10 loop
@SuppressWarnings("null")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String favoriteSweet = null;
System.out.println("which is your favorite sweet");
favoriteSweet = sc.nextLine();
switch(favoriteSweet)
{
case "rasgulla":
System.out.println("I love rasgulla");
break;
case "rabri":
System.out.println("I love rabri");
break;
case "barfi":
System.out.println("I love barfi");
break;
case "kaju_katli":
System.out.println("I love kaju_katli");
break;
default:
System.out.println("please enter a valid value");
}
}
}
If you will not use break keyword after each case all cases will execute from current case till default break acts a civilized form of goto statement.
Continue- Sometimes you want to skip the particular statement in a loop(iteration) and wants to run the loop as it is for the remaining iterations then you can go with the continue statement statement in java to better understand this let's see how it is used in a code with a good example-
program 5- "To print the odd numbers from one to ten by running a for loop from one to ten" .
problem statement- You have to run a for loop from 1 to 10 and print all odd numbers between 1 to 10 and skip the even numbers .
public class Myloop {
//show oddnumbers from one to ten in a 1 to 10 loop
@SuppressWarnings("null")
public static void main(String[] args) {
for(int i=1;i<=10;i++)
{
if(i%2==0)//it will skip all the even numbers
{
continue;
}
else
{
System.out.println(i+"\n");
}
}
}
}
Output: 1
3
5
7
9
1
3
5
7
9
what actually happens here is when i=2 which is divisible by 10 is skipped by continue statement and for loop starts executing again from i=3 similarly for other even numbers (hope it helps).
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.