Decision Making Statements in Java | if-else statements




Decision making statements in Java are used to make decisions based on certain conditions. 


The most commonly used decision making statements are:


if-else statement: The if-else statement is used to execute a block of code if a certain condition is true and another block of code if the condition is false.


if (condition) {
   // code to be executed if condition is true
} else {
   // code to be executed if condition is false
}
 


For example:


int age = 18;
if (age >= 18) {
   System.out.println("You are eligible to vote.");
} else {
   System.out.println("You are not eligible to vote.");
}




if-else if-else statement: The if-else if-else statement is used to test multiple conditions and execute a block of code based on the first true condition.


if (condition1) {
 
   // code to be executed if condition1 is true
 
} else if (condition2) {
 
   // code to be executed if condition1 is false and condition2 is true
 
} else {
 
   // code to be executed if both condition1 and condition2 are false
 
}


For example:


int marks = 75;
 
if (marks >= 90) {
 
   System.out.println("Grade: A");
 
} else if (marks >= 75) {
 
   System.out.println("Grade: B");
 
} else {
 
   System.out.println("Grade: C");
 
}




switch statement: The switch statement is used to test multiple conditions and execute a block of code based on the matching case value. The switch statement is similar to the if-else if-else statement but is often used when there are many conditions to test. The syntax for the switch statement is:


switch (expression) {
   case value1:
      // code to be executed if expression is equal to value1
      break;
   case value2:
      // code to be executed if expression is equal to value2
      break;
   ...
   default:
      // code to be executed if expression is not equal to any of the case values
}
 


It's worth noting that the break statement is mandatory in the case block.
For example:


char grade = 'B';
switch (grade) {
   case 'A':
      System.out.println("Excellent");
      break;
   case 'B':
      System.out.println("Good");
      break;
   case 'C':
      System.out.println("Average");
      break;
   default:
      System.out.println("Invalid Grade");
}

 

 


Post a Comment

Post a Comment (0)

Previous Post Next Post