In Java programming, decision-making statements allow you to control the flow of your code based on certain conditions. These statements help you create dynamic and flexible programs by executing different blocks of code depending on the evaluation of specific conditions. In this article, we will explore four essential decision-making statements in Java: if, if-else, if-else if, and nested if-else. We will delve into their syntax, and usage, and provide practical examples to enhance your understanding.
1. The if Statement:
The if statement is the most basic decision-making statement
in Java. It allows you to execute a block of code if a specified condition is
true. Here's the syntax:
if (condition) {
// Code to
execute if the condition is true
}
Here expression is a boolean expression (returns
either true or false).
·
If
the expression is evaluated to true, statement(s) inside the
body of if (statements inside parenthesis) are executed.
·
If
the expression is evaluated to the false, statement(s) inside the
body of if is skipped from execution.
The following code snippets show both situations i.e. when the expression is true and false.
Let's consider a simple example that demonstrates the if
statement:
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
Explanation:
In the provided example, we have a variable age with a value
of 18. The if statement checks if the age is greater than or equal to 18. If
the condition is true, the code inside the if block is executed, and it prints
the message "You are eligible to vote."
Note: If we do not provide the curly braces ‘{‘ and ‘}’ after if(
condition ) then by default if statement will consider the immediate one
statement to be inside its block. For example,
Here if the condition is true if block will consider
only the statement1 to be inside its block.
if(condition)
statement1;
statement2;
if (10 > 15)
System.out.println("10
is less than 15");
//
The following statement will be executed
//
as if considers one statement by default
System.out.println("I
am not in if");
When you run the program, the output will be:
I am not in if
Java if practice program 1:
Write a Java program that asks the user to enter a number
and displays the absolute value of that number.
import java.util.Scanner;
public class AbsoluteValue {
public static
void main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number
= scanner.nextInt();
int
absoluteValue;
if (number
>= 0) {
absoluteValue = number;
} else {
absoluteValue = -number;
}
System.out.println("The absolute value of " + number + "
is " + absoluteValue);
}
}
Explanation:
The program starts by importing the Scanner class
from the java.util package to read user input. Inside the main
method, a Scanner object called scanner is created to read user
input. The program uses scanner.nextInt() to read an integer value
entered by the user and stores it in the number variable. The absoluteValue
variable is declared to store the absolute value of the number. The program
uses an if-else statement to check if the number is greater than or equal to 0.
If the number is greater than or equal to 0, it assigns the value of number
to absoluteValue. If the number is less than 0, it assigns the negation
of the number to absoluteValue to get the absolute value. Finally,
the program displays the result using the System.out.println statement,
concatenating the original number and its absolute value.
Program's output for different inputs:
Example Run 1:
Enter a number: 5
The absolute value of 5 is 5
Example Run 2:
Enter a number: -8
The absolute value of -8 is 8
Java if practice program 2:
Write a Java program that asks the user to enter product
price and quantity and then calculate the revenue. If the revenue is more than
5000 a discount is 10% offered. The program should display the discount and net
revenue. Revenue can be calculated as the selling price of the product times
the quantity sold, i.e. revenue = price × quantity.
Solution:
import java.util.Scanner;
public class RevenueCalculator {
public static
void main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter the product price: ");
double
price = scanner.nextDoubfle();
System.out.print("Enter the quantity sold: ");
int
quantity = scanner.nextInt();
double
revenue = price * quantity;
double
discount = 0;
double
netRevenue = revenue;
if (revenue
> 5000) {
discount = 0.1 * revenue;
netRevenue = revenue - discount;
}
System.out.println("Revenue: $" + revenue);
System.out.println("Discount: $" + discount);
System.out.println("Net Revenue: $" + netRevenue);
}
}
Explanation:
The program calculates the revenue by multiplying the price
and quantity variables and stores it in the revenue variable. It initializes
the discount and netRevenue variables to 0 and the initial revenue value,
respectively. The program checks if the revenue is greater than 5000 using an
if statement. If the condition is true, it calculates the discount as 10% of
the revenue and subtracts it from the revenue to get the netRevenue. Finally,
the program displays the revenue, discount, and net revenue using the System.out.println
statement.
Output:
Enter the product price: 20
Enter the quantity sold: 30
Revenue: $600.0
Discount: $0.0
Net Revenue: $600.0
2. The if-else Statement:
The if-else statement allows you to execute a block of code
if a condition is true and an alternative block of code if the condition is
false. Here's the syntax:
if (condition) {
// Code to
execute if the condition is true
} else {
// Code to
execute if the condition is false
}
Let's use an example to illustrate the if-else
statement:
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote.");
} else {
System.out.println("You are not eligible to vote yet.");
}
Explanation:
In the if-else example, we have the same variable age with a
value of 18. The if condition checks if the age is greater than or equal to 18.
If the condition is true, it executes the code inside the if block, printing
the message "You are eligible to vote." If the condition is false, it
executes the code inside the else block, printing the message "You are not
eligible to vote yet."
Java if-else practice program:
Write a Java program to determine if you need an umbrella or
not on the basis of user's input.
Solution:
import java.util.Scanner;
public class IfElseProgram {
public static
void main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Is it raining? (Enter 'yes' or 'no'): ");
String
userInput = scanner.nextLine();
if
(userInput.equals("yes")) {
System.out.println("Take an umbrella with you!");
} else if
(userInput.equals("no")) {
System.out.println("You don't need an umbrella.");
}
}
}
Explanation:
The program prompts the user with the question "Is it
raining? (Enter 'yes' or 'no'): ". The user's input is stored in the userInput
variable using scanner.nextLine(). Next, we use an if-else statement to
check the user's input. If the user's input, regardless of case, is
"yes", the program prints "Take an umbrella with you!". If
the user's input, regardless of case, is "no", the program prints
"You don't need an umbrella.".
3. The if-else if Statement:
The if-else if statement extends the if-else statement by
allowing you to check multiple conditions. It enables you to execute different
blocks of code based on various conditions. Here's the syntax:
if (condition1) {
// Code to
execute if condition1 is true
} else if (condition2) {
// Code to
execute if condition2 is true
} else {
// Code to
execute if all conditions are false
}
Consider an example that demonstrates the if-else if
statement:
int score = 75;
if (score >= 90) {
System.out.println("Excellent!");
} else if (score >= 80) {
System.out.println("Good job!");
} else if (score >= 70) {
System.out.println("Well done.");
} else {
System.out.println("Keep practicing!");
}
Explanation:
In the if-else if example, we have a variable score with a
value of 75. The if condition checks if the score is greater than or equal to
90. If true, it prints "Excellent!" If the first condition is false,
it moves to the else if condition and checks if the score is greater than or
equal to 80. If true, it prints "Good job!" If both conditions are
false, it executes the else block and prints "Keep practicing!"
Java if-else-if practice program:
Write a program that displays the grade of the student using the following criteria.
Marks >90 = A+
Marks >80 = A
Marks >70 = B
Marks >60 = C
Marks >50 = D
Marks <50 = Fail
Solution:
public class GradeCalc {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else
if(marks>=50 && marks<60){
System.out.println("D
grade");
}
else
if(marks>=60 && marks<70){
System.out.println("C
grade");
}
else
if(marks>=70 && marks<80){
System.out.println("B
grade");
}
else
if(marks>=80 && marks<90){
System.out.println("A
grade");
}else
if(marks>=90 && marks<100){
System.out.println("A+
grade");
}else{
System.out.println("Invalid!");
}
}
}
When you run the program, the output will be:
C grade
4. Nested if-else Statements:
Nested if-else statements involve using an if-else statement
within another if or else block. This allows for more complex decision-making
scenarios.
Here's an example:
int x = 10;
int y = 5;
if (x > 0) {
if (y > 0) {
System.out.println("Both x and y are positive.");
} else {
System.out.println("x is positive, but y is not.");
}
} else {
System.out.println("x
is not positive.");
}
Explanation:
In the nested if-else example, we have two variables x and
y. The outer if condition checks if x is greater than 0. If true, it moves to
the inner if condition and checks if y is greater than 0. If both conditions
are true, it prints "Both x and y are positive." If the inner if
condition is false, it executes the else block and prints "x is positive,
but y is not." If the outer if condition is false, it executes the else
block and prints "x is not positive."
Java nested if-else practice program:
Write a program that take three numbers from the user and
print the greatest number using nested “ifs”.
Solution:
import java.util.Scanner;
public class SmallestUsingNestedIfs {
public static void
main(String[] args) {
Scanner in = new
Scanner(System.in);
System.out.print("Input the 1st number: ");
int num1 =
in.nextInt();
System.out.print("Input the 2nd number: ");
int num2 =
in.nextInt();
System.out.print("Input the 3rd number: ");
int num3 =
in.nextInt();
if (num1 < num2)
if (num1 < num3)
System.out.println("The Smallest: " + num1);
if (num2 < num1)
if (num2 < num3)
System.out.println("The Smallest: " + num2);
else if (num3 <
num1)
if (num3 < num2)
System.out.println("The Smallest: " + num3);
}
}
When you run the program, the output will be:
Input the 1st number: 25
Input the 2nd number: 78
Input the 3rd number: 87
The Smallest: 87
More Java practice Programs on Java if-else
Program 1: Odd or Even Number
Problem Statement: Write a program that asks the user to
enter a number and determines whether the number is odd or even.
Solution
import java.util.Scanner;
public class OddEvenProgram {
public static void
main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number =
scanner.nextInt();
if (number % 2
== 0) {
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}
}
}
Sample Output 1:
Enter a number: 5
5 is an odd number.
Sample Output 2:
Enter a number: 10
10 is an even number.
Program 2: Leap Year
Problem Statement: Write a program that asks the user
to enter a year and determines whether it is a leap year or not.
Solution
import java.util.Scanner;
public class LeapYearProgram {
public static void
main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year =
scanner.nextInt();
if ((year % 4
== 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
Sample Output 1:
Enter a year: 2020
2020 is a leap year.
Sample Output 2:
Enter a year: 2022
2022 is not a leap year.
Program 3: Pass or Fail
Problem Statement: Write a program that asks the user
to enter a student's score and determines whether the student has passed or
failed. The passing score is 60 or above.
import java.util.Scanner;
public class PassFailProgram {
public static void
main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter the student's score: ");
int score =
scanner.nextInt();
if (score >= 60) {
System.out.println("The student has passed.");
} else {
System.out.println("The student has failed.");
}
}
}
Sample Output 1:
Enter the student's score: 75
The student has passed.
Sample Output 2:
Enter the student's score: 40
The student has failed.
Program 4: Largest of Three Numbers
Problem Statement: Write a program that asks the user
to enter three numbers and determines the largest among them.
Solution
import java.util.Scanner;
public class LargestNumberProgram {
public static void
main(String[] args) {
Scanner
scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 =
scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 =
scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 =
scanner.nextInt();
int largest =
num1;
if (num2 >
largest) {
largest =
num2;
}
if (num3 >
largest) {
largest =
num3;
}
System.out.println("The largest number is: " + largest);
}
}
Sample Output 1:
Enter the first number: 5
Enter the second number: 8
Enter the third number: 3
The largest number is: 8
Sample Output 2:
Enter the first number: 12
Enter the second number: 2
Enter the third number: 9
The largest number is: 12
In this article, we explored four essential decision-making
statements in Java: if, if-else, if-else if, and nested if-else. These
statements enable you to control the flow of your code based on specific
conditions, making your programs more flexible and dynamic. By understanding
and effectively utilizing these statements, you can write more robust and
efficient Java code.
That concludes our discussion on Java decision-making, Java
if-else, java if-else-if, and Java nested if-else statements. Happy coding!