Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 2: An Overview of Java 27


Here is a program that illustrates theifstatement:

/*
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,xandy, 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 theforloop. The simplest form of theforloop is shown here:


for(initialization; condition; iteration)statement;

In its most common form, theinitializationportion of the loop sets a loop control variable
to an initial value. Theconditionis a Boolean expression thattests the loopcontrolvariable.
If the outcome of that test is true, theforloop continues to iterate. If it is false, the loop

Free download pdf