Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language


Variables and Data Types

class Count {
    public static void main(String args[])
        throws java.io.IOException
    {
        int count = 0;

        while (System.in.read() != -1)
            count++;
        System.out.println("Input has " + count + " chars.");
    }
}    

Variables

The character-counting program uses one local variable--count. The program increments count each time it reads a character.

Primitive Data Types

All variables in the Java language must have a data type. The Java language supports a full range of primitive data types, including integer, floating point, character, and boolean.
 Type             Size/Format
byte		 8-bit two's complement
short		16-bit two's complement
int		32-bit two's complement
long		64-bit two's complement

float		32-bit IEEE 754 floating point
double		64-bit IEEE 754 floating point

char		16-bit Unicode character

In the example program, count is an integer, as indicated by the int keyword that precedes it. A variable's data type determines its range of values, operations that can be performed on it, and the effect of those operations. For example, integers can have only whole number values (both positive and negative) and the standard arithmetic operators (+, -, etc.) perform the normal arithmetic operations (addition, subtraction, etc.).

The code "= 0" that follows the variable name initializes the variable to 0. If you try to use a variable in a program without first initializing it, the compiler issues an error message. See Troubleshooting Compiler Problems for more information.

Complex Data Types

The Java language also supports many complex data types, including arrays, strings, and objects. In addition to the predefined data types listed above, you can define your own data types through class and interface definitions. Indeed, you've already defined a class--the Count class in the character-counting program. See Missing Page . for more information about defining your own classes and interfaces.


Note to C and C++ Programmers: There are three C Data Types Not Supported By the Java Language . They are pointer, struct, and union.


Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language