Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

All About Operators 55

You also can set one variable equal to the value of another variable if they
both are of the same type. Consider the following example:


int mileage = 300;
int totalMileage = mileage;


First, an integer variable called mileageis created with a starting value of 300.
Next, an integer variable called totalMileageis created with the same value
as mileage. Both variables have the starting value of 300. In future hours, you
learn how to convert one variable’s value to the type of another variable.


As you’ve learned, Java has similar numeric variables that hold values of
different sizes. Both intand longhold integers, but longholds a larger
range of possible values. Both floatand doublecarry floating-point num-
bers, but doubleis bigger.


You can append a letter to a numeric value to indicate the value’s type, as in
this statement:


float pi = 3.14F;


The F after the value 3.14 indicates that it’s a floatvalue. If the letter is
omitted, Java assumes that 3.14 is a doublevalue. The letter Lis used for
longintegers and D for doublefloating-point values.


Another naming convention in Java is to capitalize the names of variables
that do not change in value. These variables are called constants. The follow-
ing creates three constants:


final intTOUCHDOWN = 6;
final intFIELDGOAL = 3;
final intPAT = 1;


Because constants never change in value, you might wonder why one ever
should be used—you can just use the value assigned to the constant instead.
One advantage of using constants is that they make a program easier to
understand.


In the preceding three statements, the name of the constant was capitalized.
This is not required in Java, but it has become a standard convention among
programmers to distinguish constants from other variables.


All About Operators


Statements can use mathematical expressions by employing the operators +,



  • , *, /, and %. You use these operators to crunch numbers throughout your
    Java programs.


CAUTION
If you do not give a variable a
starting value,you must give it
a value before you use it in
another statement. If you don’t,
when your program is compiled,
you might get an error stating
that the variable “may not have
been initialized.”
Free download pdf