Variables can be declared near the top of the method or in the midst of writing code. Variables can also be declared and initialized in one line. The following example program illustrates these aspects of variable declaration and initialization.
Program 3-1
public class DeclareVar
{
public static void main(String[] args)
{
// first is declared and initialized
// second is just initialized
int first = 5, second;
double x;
char ch;
boolean done;
second = 7;
x = 2.5;
ch = 'T';
done = false;
int sum = first + second;
}
}
- Multiple variables can be declared on one line.
- Initialization is accomplished with an equal (
=
) sign
- Initialization can occur at declaration time or later in the program. The variable sum was declared and used in the same line.