Translate

Friday 15 June 2012

Variable declaration in Java

Following is the general form of a variable declaration:

type var-name

Here, type specifies the type of variable being declared, and var-name is the name of the variable. If you want to declare more than one variable of the specified type, you may use comma-separated list of variable names. Java defines several data types, including integer, character, and floating-point. 
Consider the following program.

class Example
{
    public static void main(String args[])
    {
         int num;          // This declares a variable called num
         num = 100;    // This assigns num the value 100
         System.out.println("This is num: " + num);
    }
}

When you run this program, you will see the following output:

This is num: 100

The first new line in the program is shown here:
int num;     //This declares a variable called num

This line declares an integer variable called num. Java requires that variables be declared before they are used. The keyword int specifies an integer type.
In the program, the line
num = 100;    //this assigns num the value 100
assigns to num the value 100. In java, the assignment operator is a single equal sign.

The next line of code outputs the value of num preceded by the string "This is num: "
System.out.println("This is num: " + num);
In this statement, the plus sign causes the value of num to be appended to the string that precedes it, and then  the resulting string is output. This approach can be generalized. Using the + operator you can string together as many items as you want within a single println() statement.



No comments:

Post a Comment