Decision Making in Java
Decision Making statements are piece of code which evaluates the program along with the statements to be executed and observes that the condition is true or false. if the condition is true the it executes the statement and vice-versa.
Types of Decision Making statements :
- if statement :- An if statement consists of a boolean expression followed by one or more statements.
- if...else statement :- An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
- if...else if statement :- You can use one if or else if statement inside another if or else ifstatement.
- switch statement :- A switch statement allows a variable to be tested for equality against a list of values.
Example if
public class Example_if {
public static void main(String[] args) {
int a = 10;
int b = 9;
if(a>b) {
System.out.println("A is Greater than B");
}
}
}
Example if...else
public class Example_if {
public static void main(String[] args) {
int a = 21;
int b = 22;
if(a>b) {
System.out.println("A is Greater than B");
}else{
System.out.println("B is Greater Number");
}
}
}
Example if...else if
public class Example_if {
public static void main(String[] args) {
int a = 9;
int b = 22;
if(a>b) {
System.out.println("A is Greater than B");
}else if(b>a){
System.out.println("B is Greater Number");
}else {
System.out.println("Exceptional case");
}
}
}
Example switch
public class Days {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("Enter Value : ");
int day = input.nextInt();
switch(day) {
case 1:
System.out.println("Day is Monday");
break;
case 2:
System.out.println("Day is Tuesday");
break;
case 3:
System.out.println("Day is Wednesday");
break;
case 4:
System.out.println("Day is Thursday");
break;
case 5:
System.out.println("Day is Friday");
break;
case 6:
System.out.println("Day is Saturday");
break;
case 7:
System.out.println("Day is Sunday");
break;
default: System.out.println("Only 7 days in a week");
}
}
}
0 comments:
Post a Comment