Java Variables

Java Variables
Variables are are named memory locations used to store data in a program. Variables are used to store data whose value may change during program execution. For example, you can write the code shown below to compute the area for different pre-declared radii: // Computing the first area using the first radius radius = 2.0; area = radius * radius * 3.14159; System.out.println("The area is " + area + " for radius " + radius);

// Computing the second area using the second radius radius = 4.0; area = radius * radius * 3.14159; System.out.println("The area is " + area + " for radius " + radius);

Variable Declaration
Variables are used for representing data of a certain type. In order to use a variable, you need to declare it first, declaration is done by telling the compiler the name of the variable as well as what type of data it represents or is supposed to store. This is called a variable declaration, declaring a variable tells the compiler to allocate appropriate memory space for the variable based on the specified data type.

Syntax for declaring a variable: datatype variableName; Examples of variable declarations: int x;              // Declare x to be an integer variable; double radius;      // Declare radius to be a double variable; double interestRate; // Declare interestRate to be a double variable; char a;             // Declare a to be a character variable;

The examples use the data types int, double, and char. Later you will be introduced to additional data types, such as byte, short, long, float, and boolean.

If variables are of the same type, they can be declared together, as follows: datatype variable1, variable2, ..., variablen; Variables of the same data type can be declared on the same line and separated by commas (this should before the semi-colon).

Example: int i, j, k; // Declare i, j, and k as int variables

Note By convention, it is advisable that variable names are declared in lowercase. If a name consists of several words, concatenate all of them and capitalize the first letter of each word except the first letter in the variable name. Example:

double interestRate;