Java Language / Java Conditional StatementsIt tells us to execute which block / Lines of code has to be executed in the program based on the conditions.Ther are 4 conditional statements in java.They were 1. if Statement. 2. if else Statement. 3. else if Statement. 4. Ternary Operator. 5. Switch Statement. if Statement Block / Lines of code to be executed if the condition is true in if statement. Syntax if (condition) { // block / Lines of code will be executed if the condition is true }
else Statement Block1 / Lines of code will be executed if the condition is true in if statement. Block2 / Lines of code will be executed if the condition is true in else statement. Syntax if (condition) { // block1 / Lines of code to be executed if the condition is true } else { // block2 / Lines of code to be executed if the condition is false }
else if Statement Block1 / Lines of code will be executed if the condition1 is true in if statement. Block2 / Lines of code will be executed if the condition1 is false and condition2 is true. Block3 / Lines of code will be executed if the condition1 and condition2 is false. Syntax if (condition1) { // block1 code will be executed if condition1 is true } else if (condition2) { // block2 code will be executed if the condition1 is false and condition2 is true } else { // block2 code will be executed if the condition1 and condition2 are false }
Ternary Operator In the expression variable = Expression1 ? Block1 code : Block2 code if Expression1 is true it will Block1 code will be execute other wise Block2 code will be execute.
Java Switch Statements Here one of the block is executed based on Condition /switch Value which match with the case value other wise it will execute the default block. Syntax switch(Condition /switch Value) { case 1: //block1 break; case 2: // block2 break; case 3: // block3 break; default: // block4 }
|