Java if Statement
Simple if statment in java provides the conditional execution, whenever the expression is true the statement will execute otherwise it won't.
Java provides the traditional conditional statements like if, if...else..., elseif - The if statement allows the conditional execution. Whenever the primary if statement expression gets failed, it will try to execute the consecutive elseif block statment or the else block statement.
Simple if statment in java provides the conditional execution, whenever the expression is true the statement will execute otherwise it won't.
Find the value of a is greater than the value of b and print the message. In the below example the value of a is greater than the value of b hence it will print the message provided inside the if block.
class ConditionalStatement {
public static void main(String[] args) {
int a = 6;
int b = 3;
if (a > b) {
System.out.println("The value of a is greater than the value of b");
}
}
}
Simple if...else... statement in java provides the conditional execution, whenever the expression is true the statement will execute otherwise it will execute the else block.
Check if the two numbers are equal then print the message from the if block otherwise print the message from the else block.
class ConditionalStatement {
public static void main(String[] args) {
int a = 3;
int b = 6;
if (a == b) {
System.out.println("Both the numbers are equal");
} else {
System.out.println("Both the numbers are NOT equal");
}
}
}
if...elseif... statement in java provides the conditional execution, whenever the primary expression is true then the statements under if block will execute otherwise it will check the consecutive elseif expression and executes the respective block if its true otherwise it will execute the else block if exist.
Find the suitable programming language and print the greeting message in the console using elseif statement.
class ConditionalStatement {
public static void main(String[] args) {
String language = "Java";
if (language == "C") {
System.out.println("Welcome to the world of 'C'");
} else if (language == "Java") {
System.out.println("Welcome to the world of 'Java'");
} else if (language == "Kotlin") {
System.out.println("Welcome to the world of 'Kotlin'");
} else {
System.out.println("None of the languages selected");
}
}
}
The nested if statement in java provides the conditional execution inside another if statement.
Find the student's category from the mark using nested if statement.
class ConditionalStatement {
public static void main(String[] args) {
int mark = 60;
if (mark <= 50) {
if(mark < 30) {
System.out.println("Below average");
} else {
System.out.println("Average");
}
} else if (mark < 75) {
if(mark < 60) {
System.out.println("Performer");
} else {
System.out.println("Good Performer");
}
} else {
System.out.println("Out Standing");
}
}
}