|
Day 4: Object Lessons
NOTES AND CORRECTIONS
SOURCE FILES
READER QUESTIONS
- Q: In your book, you use so many methods, such as
length(), charAt(), indexOf() and so on. How
do we find these useful methods if we are beginners and don't know
what methods exist? -- C.Y.
A: The book covers a wide cross-section of the most useful
methods in the Java class libraries, but you'll need to expand
beyond these when developing your own programs. Sun offers
full
Java 1.2 documentation on its Java site. Also, if David
Flanagan publishes a new version of Java in a Nutshell for
version 1.2 of the language, you should look for a copy. His
Java
1.1 in a Nutshell and Java in a Nutshell (for version
1.0) are always within reach of my computer; they offer a quick
and thorough reference to all classes and methods that comprise
the Java language.
- Q: Page 96 shows examples of nested method calls such
as myCustomer.cancelAllOrders().talkToManager();. I'm
having a difficult time grasping nested methods with more than a
single level. What would a class sample look like with a method
call like the one above? -- K.A.F.
A: In the preceding example, the most confusing part is
probably cancelAllOrders(). This is a method of the
myCustomer object that returns an object. The object that
it returns has a talkToManager() method. The ShowNesting.java
file shows how this specific nested method call could work in a
simple Java application. It compiles into three files: ShowNesting.class,
CustomerManager.class,
and OrderManager.class.
- Q: I've got the following question about the line found in Day 4; Page 102:
"The exception is casting integers to floating point values -- casting an int
or a long to a float, or a long to a double can
cause some loss of precision."
How can an integer lose precision when it doesn't have it to begin with (in
other words, it's not a real number)? -- P. R.
A: The loss of precision occurs because integer types can hold more
whole numbers than floating-point types. For this reason, you run into a
loss of precision when casting very large int and long values
to float and very large long values to double.
Both int and float are 32-bit values
in Java. The int primitive data type can represent 2.14 trillion
different whole numbers, but float can only represent around 16.78
million whole numbers, because it also has to represent other values. When
you cast an int value higher than 16,777,216 to a float,
because of how Java applies the rules of floating-point arithmetic, the int
value will be converted to the closest whole number that float can
represent.
To see this in action, write an application with
the following code:
int i = 2000000000;
float one = i;
float two = i + 5;
if (one == two)
System.out.println("Numbers are equal.");
else
System.out.println("Numbers are not equal.");
This will display the string "Numbers
are equal." If you change the first line to int i = 16777216 ,
the code will display the string "Numbers are not equal."
LINKS
|