Chapter 5
Control Statements
|
Programming language uses control statements to cause
the flow of execution to advance and branch based on changes to the state
of a program. Java’s Control statements can be classified in two categories.
Selection
|
|
Iteration
|
if(
)
else |
|
While() |
switch(
)
case |
|
Do
While(); |
|
|
For(
; ; ) |
if
If statement can be used route program execution
through two different paths.
if ( condition ) statement1;
else statement2;
The if works like this: If the condition is true,
then statement1 is executed. Otherwise statement2 (if it exists) is executed.
In no case will both statements be executed.
class example1 {
public static void main ( String args[ ] ) {
int a = 20;
int b = 30;
if ( a < b )
System.out.println("a is greater than b");
else
System.out.println("b is greater than a");
}
} |
since ( a > b ) is false.
Comparison operators returns boolean values (true/false)
which decides what statement is to be executed. One can also put boolean
variables in condition for direct comparisons.
class example2 {
public static void main ( String args[ ] ) {
boolean ans = true;
if ( ans )
System.out.println("ans is true");
else
System.out.println("ans is false");
}
} |
above program displays ans is true.
Nested if
class example3 {
public static void main(String args[ ] ) {
x = 20;
if ( x > 7 )
System.out.println( " x is greater than 7 ");
else
if ( x < 7 )
System.out.println(" x is less than 7 ");
else
System.out.println(" x is equals to 7 ");
}
} |
....................Page
under Construction................
|
|