Control Statments

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.
Selection
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:
if (condition)
statement1;
else
statement2;
The above format shows that an else statement will be executed whenever an if statement evaluates to false.
For instance,
if (a>1){
System.out.println("greater than 1");
}
else{
System.out.println("smaller than 1");
}
Lets have a look at a slightly different example as
shown below:
class compare{
public static void main(String[] args){
int a = 20;
int b = 40;
if (a<b){
System.out.println(a);
}
else{
System.out.println(b);
}
}
}
|
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.
C:\javac>javac compare.java
C:\javac>java compare
40 |

|
Current Comments
1 comments so far (post your own) View All Comments Latest 10 Comments:I am a java programming language teacher in DBU,Ethiopia. and it helps me more and more and I like it simple and understandable approach
Posted by Zeleke A. on Thursday, 03.27.08 @ 20:57pm | #54516