2.5. Assignment Statements and Assignment Expressions

 
[Page 31 ( continued )]

2.4. Variables

Variables are used to store data in a program. In the program in Listing 2.1, radius and area are variables of double-precision, floating-point type. You can assign any numerical value to radius and area , and the values of radius and area can be reassigned. For example, you can write the code shown below to compute the area for different radii:

  // Compute the first area  radius =   1.0   ; area = radius * radius * 3.14159; System.out.println(   "The area is "   + area +   " for radius "   + radius);  // Compute the second area  radius =   2.0   ; area = radius * radius * 3.14159; System.out.println(   "The area is "   + area +   " for radius "   + radius); 

2.4.1. Declaring Variables

Variables are for representing data of a certain type. To use a variable, you declare it by telling the compiler the name of the variable as well as what type of data it represents. This is called a variable declaration . Declaring a variable tells the compiler to allocate appropriate memory space for the variable based on its data type. The syntax for declaring a variable is:

 datatype variableName; 

Here are some 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;  


[Page 32]

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; 

The variables are separated by commas. For example,

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

Note

By convention, variable names are in lowercase. If a name consists of several words, concatenate all of them and capitalize the first letter of each word except the first. Examples of variables are radius and interestRate .


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net