Course Content‎ > ‎Session 2‎ > ‎

Assigning Values to Variables

How can you assign values to variables?

Use  = i.e. assignment operator, to assign value to a variable. A variable can be assigned a value as shown below:

    Variable_Name = value;

Some examples of assigning a value to a variable are:

    Choice = 'Y';

    age = 40;

    Balance = 2302.43F;  // assigning a value to a float type of variable

    initial_value = 0;

    Flag = true;  // Flag is a boolean type of variable

An assignment operation implies that the value of the variable on the left of the equal sign is set equal to the value on the right side.  Once a variable has been declared,  a variable has to be initialized. Assigning an initial value to a variable is called as Initialization. We can assign a value to a variable at the time of the declaration itself, as shown below:

    int count = 0;

Java permits multiple assignments in one line, as shown below:

    count = 0; age = 30; Flag = false;

Java permits assigning the same value to multiple variables of the same type, in the same line:                       

    count = total = salary = 0;

Here count, total and salary are three variables of same data type and they have been assigned the value 0. You should never have uninitialized variables in your program, otherwise the compiler will complain about it. Given below is a Java application that will show how to use variables in a program:

class VarDemo
{
    public static void main(String[ ] args)
    {
        int in1 = 90, in2 = 392;
        float fl = 232.2939F;
        char ch;
        double db;
        boolean flag;
        ch = 'd';
        db = 29.2929282;
        flag = false;  
        System.out.println("value of int variable in1 is "+in1);
        System.out.println("value of int variable in2 is "+in2);
        System.out.println("value of float variable fl is "+fl);
        System.out.println("value of char variable ch is "+ch);
        System.out.println("value of double variable db is "+db);
        System.out.println("boolean variable flag is "+flag);
         
        in1 = 12; flag = true;
        System.out.println("Now the value of integer variable in1 is " + in1);
        System.out.println("Now the value of boolean variable flag is " + flag);  
    }
}
Comments