Here is a program that illustrates the if statement:
/*
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.
The for Loop
As you may know from your previous programming experience, loop statements are an
important part of nearly any programming language. Java is no exception. In fact, as you
will see in Chapter 5, Java supplies a powerful assortment of loop constructs. Perhaps the
most versatile is the for loop. The simplest form of the for loop is shown here:
for(initialization; condition; iteration) statement;
In its most common form, 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
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home