Java Reference
In-Depth Information
variables will be more meaningful in the context of the next chapter because their primary use is in decision
making and modifying the execution sequence in a program.
EXERCISES
1. Write a console program to define and initialize a variable of type byte to 1, and then successively
multiply it by 2 and display its value 8 times. Explain the reason for the last result.
2. Write a console program to declare and initialize a double variable with some value such as
1234.5678. Retrieve the integral part of the value and store it in a variable of type long , and retrieve
the first four digits of the fractional part and store them in an integer of type short . Display the value
of the double variable by outputting the two values stored as integers.
3. Write a program that defines a floating-point variable initialized with a dollar value for your income
and a second floating-point variable initialized with a value corresponding to a tax rate of 35 percent.
Calculate and output the amount of tax you must pay with the dollars and cents stored as separate in-
teger values (use two variables of type int to hold the tax, perhaps taxDollars and taxCents ).
4. The diameter of the sun is approximately 865,000 miles. The diameter of Earth is approximately
7600 miles. Use the methods in the class Math to calculate the following:
• The volume of Earth in cubic miles
• The volume of the sun in cubic miles
• The ratio of the volume of the sun to the volume of Earth
• WHAT YOU LEARNED IN THIS CHAPTER
TOPIC
CONCEPT
Primitive
types
Primitive types are types that are built in to the Java language. Variables of the primitive types store nu-
merical values that are integers or floating-point values, boolean values, or Unicode characters.
Integer
types
The integer types are byte , short , int , and long , and variables of these types occupy 1, 2, 4, and 8
bytes, respectively.
Storing
characters
Variables of type char occupy 2 bytes and can store a single Unicode character code.
Storing lo-
gical values
Variables of type boolean can have only the value true or the value false .
Floating-
point types
The floating-point types are float and double , occupying 4 and 8 bytes respectively.
Integer cal-
culations
Integer expressions are evaluated using 64-bit operations for variables of type long and using 32-bit op-
erations for all other integer types. You must, therefore, add a cast for all assignment operations storing a
result of type byte , type short , or type char .
Floating-
point calcu-
lations
A floating-point operation can produce a result that is outside the range of the type of the result. Values
that are outside the range of a floating-point type are represented by a special value that is displayed as
either Infinity or -Infinity . The result of a floating-point operation can also be indeterminate, which
is displayed as NaN .
Search WWH ::




Custom Search