In this chapter you will learn:
- What is Decision Making in Java?
- What is If else Statement?
- What is switch case statement?
- Programming Example
What is Decision Making in Java?
Decision Making is a process in which a condition is evaluated and based on true/false result program gets direction to execute. Mainly If-else and switch case statements are responsible for decision making in Java.
What is If Else Statement?
If Else statement is primary decision making or branching control in Java. It tests a condition and return Boolean value (true or false) as output. If the output is true the if block executed otherwise else block gets executed. You can understand it with this picture.
Syntax
if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
Programming Example
class IfElse { public static void main(String[] args) { int num1, num2; num1=10; num2=12; //In this program Else block gets executed if(num1>num2) { System.out.println(num1 + "is greater than " + num2); } else { System.out.println(num2 + " is greater than " + num1); } } }
Output
D:\JavaProgram>javac IfElse.java
D:\JavaProgram>java IfElse
12 is greater than 10
D:\JavaProgram> __
What is Switch Case Statement in Java?
If you have to use multiple if else statement you can use switch case statement instead of it. In switch case statement there is a condition inside a switch and a list of condition in case. When a case condition matches with switch condition the program executes the particular case condition.
Syntax
switch(expression){ case value : //Statements break; //optional case value : //Statements break; //optional //You can have any number of case statements. default : //Optional //Statements }
Programming Example
import java.util.Scanner; class SwitchCase { public static void main(String[] args) { String DayName; System.out.println("Enter a Day Name in small letter:"); //Getting Input from user Scanner scan=new Scanner(System.in); DayName=scan.nextLine(); switch(DayName) { case "sunday": { System.out.println("wooo... hoooo.... It's Sunday"); break; } case "monday": { System.out.println("oh no! Its Monday"); break; } case "tuesday": { System.out.println("Again Tuesday"); break; } case "wednesday": { System.out.println("Wednesday is so boring.."); break; } case "thursday": { System.out.println("Thursday!!! Thursday!!! Thursday!!!"); break; } case "friday": { System.out.println("It's Friday Now!!!"); break; } case "saturday": { System.out.println("It's Saturday.. Party Night!!!"); break; } default: { System.out.println("Invalid Day Name"); } } } }
Output
D:\JavaProgram>javac SwitchCase.java
D:\JavaProgram>java SwitchCase
Enter a Day Name in small letter:
saturday
It’s Saturday.. Party Night!!!
D:\JavaProgram> __