Wednesday, February 25, 2015

Two Control Statement

1. The if Statement
The java if statement works much like the IF statement in any other language.  Its simplest form is;

if(condition) statement;

Here, condition is a Boolean expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed.
 Here is an example:

if(num < 100) System.out.println("num is less than 100");

In this case, if num contains a value that is less than 100, the conditional expression is true, and println( ) will execute. If num contains a value greater than or equal to 100, then the println( ) method is bypassed.

Here are a few conditional expression.
Operator
Meaning
< 
Less than
> 
Greater than
==
Equal to

 Notice that the test for equality is the double equal sign.

/*
Demonstrate the if.
Call this file "IfSample.java".
*/
class IfSample {
        public static void main(String args[]) {
                int x, y;
                x = 10;
                y = 20;

                 if(x < y) System.out.println("x is less than y");
                 x = x * 2;

                 if(x == y) System.out.println("x now equal to y");
                 x = x * 2;
  
                 if(x > y) System.out.println("x now greater than y");
                 // this won't display anything

                  if(x == y) System.out.println("you won't see this");
        }
}
  
The output generated by this program is shown here:
x is less than y
x now equal to y
x now greater than y

Notice one other thing in this program. The line
int x, y;
declares two variables, x and y, by use of a comma-separated list.

2. The for Loop
Loop statements are an important part of nearly any programming language. Java is no exception.
The simplest form of the for loop is;

for(initialization; condition; iteration) statement;

The initialization portion of the loop sets a loop control variable to an initial value. The condition is a Boolean expression that tests the loop control variable. If the outcome of that test is true, the for loop continues to iterate. If it is false, the loop terminates. The iteration expression determines how the loop control variable is changed each time the loop iterates.

Simple program of for loop;
/*
Demonstrate the for loop.
Call this file "ForTest.java".
*/
class ForTest {
        public static void main(String args[]) {
               int x;
               for(x = 0; x<10; x = x+1)
                       System.out.println("This is x: " + x);
        }
}

This program generates the following output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9














0 comments:

Post a Comment