Java if Statement
An if statement runs its body when its condition is true.
Java uses if, else if, and else to select a branch. Each condition must have a boolean value.
Follow one branch
class Main {
public static void main(String[] args) throws Exception {
int n = 2;
if (n > 0) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
yes
A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.
An if statement runs its body when its condition is true.
Print the message when a is greater than b.
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");
}
}
}
The value of a is greater than the value of b
An if-else statement selects exactly one of its two branches.
Compare the two numbers and print the message from the matching branch.
class ConditionalStatement {
public static void main(String[] args) {
int a = 3;
int b = 6;
if (a == b) {
System.out.println("The numbers are equal");
} else {
System.out.println("The numbers are not equal");
}
}
}
The numbers are not equal
An else if chain tests conditions in order and runs the first matching branch. An optional else handles the remaining cases.
Choose a greeting based on the programming language.
class ConditionalStatement {
public static void main(String[] args) {
String language = "Java";
if ("C".equals(language)) {
System.out.println("Welcome to the world of 'C'");
} else if ("Java".equals(language)) {
System.out.println("Welcome to the world of 'Java'");
} else if ("Kotlin".equals(language)) {
System.out.println("Welcome to the world of 'Kotlin'");
} else {
System.out.println("None of the languages selected");
}
}
}
Welcome to the world of 'Java'
A nested if tests a second condition within an existing branch.
Use nested conditions to classify a student's score.
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");
}
}
}
Good Performer
Reference: Java language reference