Variable initialization and assignment

 

When we declare a variable, it is possible to give it an initial value.  Here’s an example:

 

                    int courses = 5;

                    double credits = 17.5;

 

There’s a little peculiarity when initializing the value of a variable declared as a float.  In this case, the numeric value must end with the letter ‘F’:

 

                                             float credits = 17.5F;

 

Without this extra character, the compiler would give an error that the types are incompatible.  We’ll discuss type compatibility in the next unit. 

 

If we don’t wish to initialize the value of a variable when we declare it, we may still assign it a value later on in our program using the assignment operator.  The assignment operator in Java is the ‘=’ symbol (make sure you don’t confuse that with the ‘==’ operator which checks for equality).  Here’s an example:

 

                                             int rabbits;

                    // some other Java statements

                    rabbits = 322;

 

We may also use the assignment operator to copy the value of one variable to another (from the right operand to left operand).  Consider this:

 

                                             int squirrels = 15;

                    int walnuts;

                    walnuts = squirrels;

 

After the last statement executes, the value of walnuts will also be 15.