Java Reference
In-Depth Information
NOTE There are other variables called class variables that have much longer life-
times when they are declared in a particular way. The variables PI and E in the
standard library class Math are examples of these. They hang around as long as
your program is executing. There are also variables that form part of a class object
called instance variables . You will learn more about these in Chapter 5.
LOOPS
A loop enables you to execute a statement or block of statements repeatedly. The need to repeat a block of
code arises in almost every program. If you did the first exercise at the end of the last chapter, based on what
you had learned up to that point, you would have come up with a program along the lines of the following:
public class TryExample1_1 {
public static void main(String[] args) {
byte value = 1;
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
System.out.println("Value is now "+value);
value *= 2;
System.out.println("Value is now "+value);
}
}
The same pair of statements has been entered eight times. This is a rather tedious way of doing things. If
the program for the company payroll had to include separate statements to do the calculation for each em-
ployee, it would never get written. A loop removes this sort of difficulty. You can write the method main()
to do the same as the preceding code like so:
public static void main(String[] args) {
byte value = 1;
for(int i = 0 ; i < 8 ; ++i) {
value *= 2;
System.out.println("Value is now " + value);
Search WWH ::




Custom Search