Last Updated : 22 Nov, 2024
The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not.
Example:
Java
// Java program to illustrate If statement
class GfG {
public static void main(String args[])
{
int i = 10;
// using if statement
if (i < 15)
System.out.println("10 is less than 15");
System.out.println("Outside if-block");
// both statements will be printed
}
}
10 is less than 15 Outside if-block
Dry-Running Above Example
1. Program starts.
2. i is initialized to 10.
3. if-condition is checked. 10<15, yields true.
3.a) "10 is less than 15" gets printed.
4. "Outside if-block" is printed.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Working of if statement:
Flowchart if statement:
Operation: The condition after evaluation of if-statement will be either true or false. The if statement in Java accepts boolean values and if the value is true then it will execute the block of statements under it.
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.
Example:
if(condition)
statement1;
statement2;// Here if the condition is true, if block will consider the statement
// under it, i.e statement1, and statement2 will not be considered in the if block, it will still be executed
// as it is not affected by any if condition.
Example 1:
Java
// Java program to illustrate If statement
class GFG {
public static void main(String args[])
{
String str = "GeeksforGeeks";
int i = 4;
// if block
if (i == 4) {
i++;
System.out.println(str);
}
// Executed by default
System.out.println("i = " + i);
}
}
GeeksforGeeks i = 5
Example 2: Implementing if else for Boolean values
Input:Javaboolean a = true;
boolean b = false;
// Java program to illustrate the if else statement
public class IfElseExample {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
if (a) {
System.out.println("a is true");
} else {
System.out.println("a is false");
}
if (b) {
System.out.println("b is true");
} else {
System.out.println("b is false");
}
}
}
a is true b is false
Explanation:
Overall, the if-else statement is a fundamental tool in programming that provides a way to control the flow of a program based on conditions. It helps to improve the readability, reusability, debuggability, and flexibility of the code.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4