if statements
The simplest statement in a control flow is the if
statement. If a certain test evaluates to true
, it tells your program to run a certain block of code. The code block or statement is omitted if the condition is false
.
The simplest form of the if
statement is: if(condition) statement;
The condition
must be a Boolean expression, meaning it evaluates to either true
or false
. Common relational operators used in these conditions include ==
(equal to), !=
(not equal to), >
(greater than), <
(less than), >=
(greater than or equal to), and <=
(less than or equal to). These operators all yield a boolean
result.
For example, if(10 < 11) System.out.println("10 is less than 11");
will execute the println
statement because 10 < 11
is true
.
When you need to run many statements depending on a condition, you can use curly brackets ({}
) to arrange them into a code block. Braces can improve code readability and help avoid problems when adding more statements later, but they are optional for single statements.
Here’s an example demonstrating the basic if
statement and relational operators:
class IfDemo {
public static void main(String args[]) {
int a, b, c;
a = 2;
b = 3;
if(a < b) System.out.println("a is less than b"); // a is 2, b is 3, 2 < 3 is true
// This won't display anything because a (2) is not equal to b (3)
if(a == b) System.out.println("you won't see this");
System.out.println();
c = a - b; // c contains -1
System.out.println("c contains -1");
// This won't display because c (-1) is not >= 0
if(c >= 0) System.out.println("c is non-negative");
// This will display because c (-1) is < 0
if(c < 0) System.out.println("c is negative");
System.out.println();
c = b - a; // c now contains 1
System.out.println("c contains 1");
// This will display because c (1) is >= 0
if(c >= 0) System.out.println("c is non-negative");
// This won't display because c (1) is not < 0
if(c < 0) System.out.println("c is negative");
}
}
Output:
a is less than b
c contains -1
c is negative
c contains 1
c is non-negative
if-else statement
An alternate course of action is offered by the if-else
statement in the event that the condition of the if
clause evaluates to false
. This means that one of two code blocks will always execute: either the if
block (if the condition is true
) or the else
block (if the condition is false
).
The general form of the if-else
statement is:
if (condition) {
statement(s) for true condition;
} else {
statement(s) for false condition;
}
Consider this example which assigns a grade based on a test score:
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) { // Condition: 76 >= 90 is false
grade = 'A';
} else if (testscore >= 80) { // Condition: 76 >= 80 is false
grade = 'B Nested `if` Statements
A **nested `if` statement** occurs when an `if` statement (or an `if-else` statement) is the target of another `if` or `else` clause . Nested `if`s are commonly used in programming to create more complex decision logic .
A key rule for nested `if`s is that an `else` statement **always belongs to the nearest `if` statement** that is within the same code block and is not already associated with another `else` .
Here’s a general example illustrating `else` association:
```java
if(i == 10) { // Outer if
if(j < 20) a = b; // Inner if 1
if(k > 100) c = d; // Inner if 2
else a = c; // This else refers to 'if(k > 100)'
} else a = d; // This else refers to the outer 'if(i == 10)'
Another practical example of nested if
statements is providing specific feedback for incorrect guesses in a game:
class Guess3 {
public static void main(String args[]) throws java.io.IOException {
char ch, answer = 'K';
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it: ");
ch = (char) System.in.read(); // Get a character from keyboard
if(ch == answer) System.out.println("** Right **");
else {
System.out.print("...Sorry, you're ");
// Nested if to provide more specific feedback
if(ch < answer) System.out.println("too low");
else System.out.println("too high");
}
}
}
Sample Output (if user inputs ‘Z’):
I'm thinking of a letter between A and Z.
Can you guess it: Z
...Sorry, you're too high
if-else-if Ladder
An array of nested if
statements serves as the foundation for the popular programming concept known as the if-else-if
ladder. In accordance with a number of conditions, it permits several possible execution paths.
Its typical form is:
if(condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
. . .
else // Optional
default_statement;
The conditions in the if-else-if
ladder are evaluated from top to bottom. As soon as a condition evaluates to true
, its associated statement (or block) is executed, and the rest of the ladder is bypassed. If none of the if
or else if
conditions are true
, the final else
statement (if present) will be executed as a default action. If there is no final else
and all conditions are false
, no action will take place.
Here’s an example that uses an if-else-if
ladder to print a description for a variable x
:
class Ladder {
public static void main(String args[]) {
int x;
for(x=0; x<6; x++) {
if(x==1)
System.out.println("x is one");
else if(x==2)
System.out.println("x is two");
else if(x==3)
System.out.println("x is three");
else if(x==4)
System.out.println("x is four");
else // Default case for other values of x
System.out.println("x is not between 1 and 4");
}
}
}
Output:
x is not between 1 and 4
x is one
x is two
x is three
x is four
x is not between 1 and 4
When selection criteria include ranges of values or conditions that are independent of a single integer, enumerated value, or String object unlike the switch
statement the if-else-if
ladder is especially helpful.
In Java programming, control flow statements are crucial for regulating the order in which statements are executed. However, control flow statements allow your program to deviate from this linear execution by incorporating decision-making, looping, and branching. Among these, the if
statement is a fundamental selection statement used for decision-making.