1.2. Variables
The next example prints a part of the Fibonacci sequence, an infinite sequence whose first few terms are
1 1 2 3 5 8
13
21
34
The Fibonacci sequence starts with the terms 1 and 1, and each successive term is the sum of the previous two
terms. A Fibonacci printing program is simple, and it demonstrates how to declare variables, write a simple
loop, and perform basic arithmetic. Here is the Fibonacci program:
class Fibonacci {
/* Print out the Fibonacci sequence for values < 50 /
public static void main(String[] args) {
int lo = 1;
int hi = 1;
System.out.println(lo);
while (hi < 50) {
System.out.println(hi);
hi = lo + hi; // new hi
lo = hi - lo; / new lo is (sum - old lo)
that is, the old hi /
}
}
}
This example declares a Fibonacci class that, like HelloWorld, has a main method. The first two lines
of main are statements declaring two local variables: lo and hi. In this program hi is the current term in the
series and lo is the previous term. Local variables are declared within a block of code, such as a method
body, in contrast to fields that are declared as members of a class. Every variable must have a type that
precedes its name when the variable is declared. The variables lo and hi are of type int, 32-bit signed
integers with values in the range 2^31 through 2^31 1.
The Java programming language has built-in "primitive" data types to support integer, floating-point, boolean,
and character values. These primitive types hold numeric data that is understood directly, as opposed to object
types defined by programmers. The type of every variable must be defined explicitly. The primitive data types
are:
boolean either TRue or false
char 16-bit Unicode UTF-16 character (unsigned)
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)