Java Conditions and If Statements

In this tutorial, you can learn Java Conditions and If Statements. With the help of these Conditions, users can control the flow of our program. Java provides many types of if statements, With the help of these statements you can execute different conditions. In this tutorial, we will use if statements, if-else statements, if-else-if ladder statements, and nested if statements and we will see the examples of these statements also.

if Statement in Java

if statement is used to execute a block of code if a condition is true. See below example

int age = 20;
if (age >= 18) {
System.out.println("You are eligible for voting.");
}

if-else Statement in Java:

if statement is used to execute a block of code and checks the boolean condition: true or false.

Example 1

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

Example 2

int num = 7;
if (num % 2 == 0) {
System.out.println("Number is even.");
} else {
System.out.println("Number is odd.");
}

if-else-if Ladder Statement

if-else-if ladder statement check multiple conditions one by one and execute the first matching condition. See below example

int score = 83;
if (score >= 90) {
System.out.println("You got an A.");
} else if (score >= 80) {
System.out.println("You got a B.");
} else if (score >= 70) {
System.out.println("You got a C.");
} else {
System.out.println("You need to improve your score.");
}

Nested if Statements in Java

Nested if statement is an if statement inside another if or else block. See below example

int num1 = 10;
int num2 = 15;
if (num1 > num2) {
if (num1 % num2 == 0) {
System.out.println("num1 is divisible by num2.");
} else {
System.out.println("num1 is greater than num2, but not divisible by num2.");
}
} else {
System.out.println("num1 is not greater than num2.");
}

Conclusion

We completed the many topics of Java conditions and if statements. Remember to practice writing different scenarios and conditions to gain more understanding of how if statements work.We will learn many of the java topics using this website SafitTech.com

Related Posts

Introduction of Java
Scroll to Top