Java Reference
In-Depth Information
Declaring Floating Point Variables
You declare floating point variables in a similar way to that we've already used for integers. We can
declare and initialize a variable of type double with the statement:
double sunDistance = 1.496E8;
Declaring a variable of type float is much the same. For example:
float electronMass = 9E-28F;
You can of course declare more than one variable of a given type in a single statement:
float hisWeight = 185.2F, herWeight = 108.5F;
Note that you must put the F or f for literals of type float . If you leave it out, the literal will be of type
double , and the compiler won't convert it automatically to type float .
Now that we know how to declare and initialize variables of the basic types, we are nearly ready to
write a program. We just need to look at how to calculate and store the results of a calculation.
Arithmetic Calculations
You store the result of a calculation in a variable by using an assignment statement. An assignment
statement consists of a variable name followed by an assignment operator, followed by an arithmetic
expression, followed by a semicolon. Here is a simple example of an assignment statement:
numFruit = numApples + numOranges; // Calculate the total fruit
Here, the assignment operator is the = sign. The value of the expression to the right of the = sign is
calculated and stored in the variable that appears to the left of the = sign. In this case, the values in the
variables numApples and numOranges are added together and the result is stored in the variable
numFruit . Of course, we would have to declare all three variables before this statement.
Incrementing a variable by a given amount is a common requirement in programming. Look at the
following assignment statement:
numApples = numApples + 1;
The result of evaluating the expression on the right of the = is one more than the value of numApples .
This result is stored back in the variable numApples , so the overall effect of executing the statement is
to increment the value in numApples by 1 . We will see an alternative, more concise, way of producing
the same effect shortly.
You can write multiple assignments in a single statement. Suppose you have three variables a , b , and c ,
of type int , and you want to set all three to 777. You can do this with the statement:
a = b = c = 777;
Search WWH ::




Custom Search