In general, you must give a variable a value prior to using it. One way to give a variable a value is through an assignment statement, as you have already seen. Another way is by giving it an initial value when it is declared. To do this, follow the variable’s name with an equal sign and the value being assigned. The general form of initialization is shown here:
type var=value;
Here,value is the value that is given to var when var is created. The value must be compatible with the specified type. Here are some examples:
int count = 10;
// give count an initial value of 10
char ch = 'X';
// initialize ch with the letter X
float f = 1.2F;
// f is initialized with 1.2
When declaring two or more variables of the same type using a comma-separated list, you can give one or more of those variables an initial value.
For example:
int a,
b = 8,
c = 19,
d;
// b and c have initialization
In this case, only band care initialized.
Dynamic Initialization
Although the preceding examples have used only constants as initializes, Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.
For example, here is a short program that computes the volume of a cylinder given the radius of its base and its height:
// Demonstrate dynamic initialization.
class DynInit
{
public static void main(String args[])
{
double radius = 4,
height = 5;
// dynamically initialize volume
double volume = 3.1416 * radius * radius * height;
System.out.println("Volume is " + volume);
}
}
Here, three local variables—radius,height, and volume—are declared. The first two,radius and height, are initialized by constants. However,volume is initialized dynamically to the volume of the cylinder. The key point here is that the initialization expression can use any element valid at the time of the initialization, including calls to methods, other variables, or literals.
0 comments:
Post a Comment