Java if-else statement;-
It is used to check the condition is true or false.
Various types of if-else statement:-
- if statement.
- if-else statement.
- if-else-if ladder.
- nested if statement.
If statement;-
It executes the if block if condition is true otherwise not executed.
Syntax of the if statement;-
If(test the expression)
{
// statements to be executed if the test expression is true.
}
Example-
class Student
{
public static void main(String[] args)
{
int age=25; if(age>18) { System.out.println(“Eligible for Vote”); } } } Output- Eligible for Vote.
If-else statement;-
It executes if part if the condition is true otherwise they execute else part.
Syntax-
if (test expression) { // statements to be executed if the test expression is true } else { // statements to be executed if the test expression is false }
Example-
class Student { public static void main(String args[]) { int a=10; if(a%2==0) { System.out.println(“number is even”); } else { System.out.println(“number is odd”); } } } Output- number is even.
if-else-if ladder;-
The if...else ladder allows you to check between multiple test expressions and execute different statements.
Syntax-
if (test expression1) { // statement(s) } else if(test expression2) { // statement(s) } else if (test expression3) { // statement(s) } . . else { // statement(s) }
Example-
class Student { public static void main(String args[]) { int age=38; if(age>90) { System.out.println("dead"); } else if(age>=0 && age<12) { System.out.println("child"); } else if(age>=13 && age<22) { System.out.println("teenager"); } else if(age>=23 && age<50) { System.out.println("younger"); } else if(age>=51&& age<89) { System.out.println("older"); } } } Output- Younger.
nested if statement-;
The nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true.
Syntax:
if(condition){ //code to be executed if(condition){ //code to be executed } }
Example-
class Student { public static void main(String args[]) { int age=30; int weight=70; if(age>=18) { if(weight>55) { System.out.println("You are eligible to donate blood"); } } } } Output- You are eligible to donate blood.
Can you answer this question?
Answer
0 Answers