Programming References and tutorials for Developers.

Declaring a Variable in Java

By The Saint on Saturday, April 04, 2009

Filed Under:

Declaring a Variable in Java
Variables were introduced in Module 1. Here, we will take a closer look at them. As you learned earlier, variables are declared using this form of statement,

type var-name;

where type is the data type of the variable, and var-name is its name. You can declare a variable of any valid type, including the simple types just described. When you create a variable, you are creating an instance of its type. Thus, the capabilities of a variable are determined by its type. For example, a variable of type boolean cannot be used to store floating-point values. Furthermore, the type of a variable cannot change during its lifetime. An int variable cannot turn into a char variable, for example.

All variables in Java must be declared prior to their use. This is necessary because the compiler must know what type of data a variable contains before it can properly compile any statement that uses the variable. It also enables Java to perform strict type checking.

Initializing a Variable
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 = 150; // give count an initial value of 150
char ch = 'X'; // initialize ch with the letter X
float f = 10.5F; // f is initialized with 10.5
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 = 20, c = 35, d; // b and c have initializations

In this case, only b and c are initialized.

0 comments for this post