While writing code in any language, you will have to control the flow of your program - you will want to execute a certain piece of code if a condition is satisfied, and some different code in case it is not.
If
statements are used to make these decisions in code. The keyword if
tells Java to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as boolean
conditions and they may only be true or false.
When the condition evaluates to true, the program executes the statement inside the curly braces. When the boolean condition evaluates to false, the statement inside the curly braces will not execute. But what will happen then?
Normally nothing would happen. But with an else
statement, an alternate block of code can be executed.
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
When writing if
statements, we usually compare two values using one or more comparison operators:
Operator | Name | Examples |
---|---|---|
== | Equal | x == 5, x == y |
!= | Not equal | x != 3, x != y |
> | Greater than | x > 5, x > y |
< | Less than | x < 8, x < y |
>= | Greater than or equal to | x >= 4, x >= y |
<= | Less than or equal to | x <= 3, x <= y |
We can also combine multiple conditional statements with the help of logical operators:
Operator | Name | Description | Examples |
---|---|---|---|
&& | And | Returns true if both statements are true | x < 5 && x < 10 |
|| | Or | Returns true if one of the statements is true | x < 5 || x < 10 |
! | Not | Reverses the result, returns false if the result is true | !(x < 5 && x < 10) |
Let's go through some examples together to better understand how if-else statements work:
# Declare 2 variables and initialize them
int a = 2;
int b = 3;
// Prints "a equals 2"
if(a == 2) {
System.out.println("a equals 2");
}
// Prints nothing
if(b != 3) {
System.out.println("b is not equal to 3");
}
// Prints "b equals 3"
if(a == 2 && b - a == 1) {
System.out.println("b is equal to 3");
}
// Prints "a = 2, b = 3"
if(a != 2 || b != 3) {
System.out.println("Inside if");
}
else {
System.out.println("a = 2, b = 3");
}
// Prints "a + b equals 5"
if(!(a + b == 5)) {
System.out.println("a + b is not equal to 5");
}
else {
System.out.println("a + b equals 5");
}
// Prints "a is even, b is odd"
if(a % 2 == 0) {
if(b % 2 == 0) {
System.out.println("Both a and b are even");
}
else {
System.out.println("a is even, b is odd");
}
}
else {
if(b % 2 == 0) {
System.out.println("a is odd, b is even");
}
else {
System.out.println("Both a and b are odd");
}
}
Assignment
Follow the Coding Tutorial and let's write some if-else statements.
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the concept of if
statements in Java. These statements are fundamental for controlling the flow of a program based on certain conditions. Understanding how to use if
statements effectively is crucial for making decisions in your code, which is a common requirement in many programming scenarios.
Common scenarios where if
statements are particularly useful include validating user input, controlling the flow of a game, and handling different cases in business logic.
The if
statement in Java allows you to execute a block of code only if a specified condition is true. This condition is a boolean expression, meaning it evaluates to either true
or false
. If the condition is true, the code inside the if
block runs; otherwise, it is skipped.
Here is a simple example:
int number = 10;
if (number > 5) {
System.out.println("The number is greater than 5");
}
In this example, the condition number > 5
evaluates to true, so the message "The number is greater than 5" is printed.
Let's delve deeper into the key concepts and techniques involved in using if
statements:
==
(equal to), !=
(not equal to), >
(greater than), <
(less than), >=
(greater than or equal to), and <=
(less than or equal to).&&
(and), ||
(or), and !
(not).else
statement allows you to specify an alternate block of code to run if the condition in the if
statement is false.Here is an example that combines these concepts:
int age = 20;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
In this example, the condition age >= 18
evaluates to true, so the message "You are an adult." is printed. If the condition were false, the message "You are a minor." would be printed instead.
Let's look at some more examples to see how if
statements can be used in various contexts:
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
In this example, the program assigns a grade based on the value of score
. This demonstrates how multiple if
and else if
statements can be used to handle different cases.
When using if
statements, it's important to be aware of common mistakes and follow best practices:
if
statements can make your code hard to read and maintain. Consider using logical operators or breaking the code into smaller functions.{}
even for single-line statements. This improves readability and reduces the risk of errors.Once you are comfortable with basic if
statements, you can explore more advanced techniques:
switch
statement for better readability and performance.?:
provides a shorthand way to write simple if-else
statements.Here is an example of the ternary operator:
int number = 10;
String result = (number % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
In this example, the ternary operator checks if number
is even or odd and assigns the appropriate string to result
.
Let's implement a more comprehensive example that demonstrates the use of if
statements:
public class IfStatementExample {
public static void main(String[] args) {
int temperature = 25;
// Check if temperature is above 30
if (temperature > 30) {
System.out.println("It's hot outside.");
} else if (temperature >= 20 && temperature <= 30) {
System.out.println("The weather is nice.");
} else {
System.out.println("It's cold outside.");
}
// Check if temperature is exactly 25
if (temperature == 25) {
System.out.println("The temperature is exactly 25 degrees.");
}
}
}
In this example, we check the value of temperature
and print different messages based on its value. This demonstrates how to use multiple if
and else if
statements to handle different conditions.
When working with if
statements, debugging and testing are crucial to ensure your code works as expected:
if
blocks to check which conditions are being met.Here is an example of a simple test case:
public class IfStatementTest {
public static void main(String[] args) {
testTemperature(35); // Expected output: "It's hot outside."
testTemperature(25); // Expected output: "The weather is nice." and "The temperature is exactly 25 degrees."
testTemperature(15); // Expected output: "It's cold outside."
}
public static void testTemperature(int temperature) {
if (temperature > 30) {
System.out.println("It's hot outside.");
} else if (temperature >= 20 && temperature <= 30) {
System.out.println("The weather is nice.");
} else {
System.out.println("It's cold outside.");
}
if (temperature == 25) {
System.out.println("The temperature is exactly 25 degrees.");
}
}
}
When approaching problems that require if
statements, consider the following strategies:
if
statements to improve your problem-solving skills.In this lesson, we covered the basics of if
statements in Java, including comparison and logical operators, the else
statement, and advanced techniques like the ternary operator. We also discussed common pitfalls, best practices, and provided examples to illustrate these concepts.
Mastering if
statements is essential for controlling the flow of your programs and making decisions based on conditions. Practice writing if
statements in different scenarios to become more proficient in using them.
For further reading and practice, consider the following resources: