Declarations

index
BASIC

All variables used in a program must be declared. When a variable is declared, it is given a type and (optionally) an initial value. The syntax is:

type variableName = initialValue;

(where initialValue is of the correct type), or just:

type variableName;

Here are some examples:

int count = 0;
double radius = 3.5;
double diameter = 2 * radius;
String greeting = "Hello";
Person defendant = new Person("John Smith");

As in the diameter example above, the initial value may be an expression, provided that the values of all the variables in the expression have been given values earlier (higher up) in the program.

Every variable also has a scope, which is the part of the program in which the variable may be used. The scope of a variable depends on where in the program it is declared. Most often, a variable can be used starting at its declaration and extending to the end of the block in which it is declared (indicated by the next closing brace).


There are other, unrelated types of declarations: package "statements", import "statements", and methods. Normally, however, the unqualified term "declaration" usually refers to a variable declaration.