Decision Making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions.
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 statement is executed otherwise not.
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 ‘’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block.
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:
10 is less than 15 Outside if-block
Time Complexity: O(1)
Auxiliary Space: O(1)
Dry-Running Example 1:
1. Program starts. 2. i is initialized to 10. 3. if-condition is checked. 10Example 2:
Java
// Java program to illustrate If statement class IfDemo < public static void main(String args[]) String str = "GeeksforGeeks" ; System.out.println(str); // Executed by default System.out.println( "i plain">+ i); OutputGeeksforGeeks i = 5Time Complexity: O(1)
Auxiliary Space: O(1)Example no 3: (Implementing if else for Boolean values)
Input - boolean a = true; boolean b = false;Program –
Java
public class IfElseExample < public static void main(String[] args) < boolean a = true ; boolean b = false ; System.out.println( "a is true" ); System.out.println( "a is false" ); System.out.println( "b is true" ); System.out.println( "b is false" ); Outputa is true b is falseExplanation-
The code above demonstrates how to use an if-else statement in Java with Boolean values.
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.
Related Articles: