We all know that the execution of the statements in a program takes place from top to bottom. We will learn how the different kinds of statement have different effects in looping like decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) in Java programming language.
The if statement: To start with controlling statements in Java, lets have a recap over the control statements in C++. You must be familiar with the if-then statements in C++. The if-then statement is the most simpler form of control flow statement. It directs the program to execute a certain section of code. This code gets executed if and only if the test evaluates to true. That is the if statement in Java is a test of any boolean expression. The statement following the if will only be executed when the boolean expression evaluates to true. On the contrary if the boolean expression evaluates to false then the statement following the if will not only be executed.
Lets tweak th example below:
if (a > 1)
System.out.println("Greater than 1");
if (a < 1)
System.out.println("Less than 1");
In the above example if we declare int a = 1, the statements will show some of the valid boolean expressions to the if statement.
We are talking about if statements here so we can't
forget the else statement here. The if statement is incomplete without
the else statement. The general form of the statement is:
The above format shows that an else statement will be executed whenever an if statement evaluates to false. For instance,
System.out.println("greater than 1");
System.out.println("smaller than 1");
Lets have a look at a slightly different example as shown below:
The above example shows that we have taken two numbers and we have to find the largest amongst them. We have applied a condition that if a<b, print 'a' else print 'a is greater'. The following is the output which we will get in the command prompt.
Recommend the tutorial