Java Reference
In-Depth Information
Don't be surprised when you see numbers that are slightly off from the expected
values.
Don't expect to be able to compare variables of type double for equality.
To follow up on the third point, consider what the preceding code would lead to if
we were to perform the following test:
if (dollars1 == dollars2) {
...
}
The test would evaluate to false because the values are very close, but not close
enough for Java to consider them equal. We rarely use a test for exact equality when
we work with double s. Instead, we can use a test like this to see if numbers are close
to one another:
if (Math.abs(dollars1 - dollars2) < 0.001) {
...
}
We use the absolute value ( abs ) method from the Math class to find the magnitude
of the difference and then test whether it is less than some small amount (in this case,
0.001 ).
Later in this chapter we'll introduce a variation on print / println called printf
that will make it easier to print numbers like these without all of the extra digits.
4.3 Text Processing
Programmers commonly face problems that require them to create, edit, examine,
and format text. Collectively, we call these tasks text processing .
Text Processing
Editing and formatting strings of text.
In this section, we'll look in more detail at the char primitive type and introduce a
new command called System.out.printf . Both of these tools are very useful for
text-processing tasks.
The char Type
The primitive type char represents a single character of text. It's legal to have vari-
ables, parameters, and return values of type char if you so desire. Literal values of
type char are expressed by placing the character within single quotes:
char ch = 'A';
 
Search WWH ::




Custom Search