Page 117 - Introduction to Programming with Java: A Problem Solving Approach
P. 117
After casting earnedPoints to a double, the JVM sees a mixed expression and promotes numOfClasses to a double. Then floating-point division takes place.
For this example, you should not put parentheses around the earnedPoints
expression. If you did so, the / operator would have higher precedence than the cast operator, and the JVM would perform division (integer division) prior to performing the cast operation.
Later in the book, we provide additional details about type conversions. You don’t need those details now, but if you can’t wait, you can find the details in Chapter 11, Section 11.4.
3.20 char Type and Escape Sequences
In the past, when we’ve stored or printed text, we’ve always worked with groups of text characters (strings),
not with individual characters. In this section, we’ll use the char type to work with individual characters. char Type
If you know that you’ll need to store a single character in a variable, use a char variable. Here’s an example that declares a char variable named ch and assigns the letter A into it.
char ch;
ch = 'A';
Note the 'A'. That’s a char literal. char literals must be surrounded by single quotes. That syntax par- allels the syntax for string literals—string literals must be surrounded by double quotes.
What’s the point of having a char type? Why not just use one-character strings for all character pro- Apago PDF Enhancer
cessing? Because for applications that manipulate lots of individual characters, it’s more efficient (faster) to use char variables, which are simple, rather than string variables, which are more complex. For example, the software that allows you to view Web pages has to read and process individual characters as they’re downloaded onto your computer. In processing the individual characters, it’s more efficient if they’re stored as separate char variables rather than as string variables.
String Concatenation with char
Remember how you can use the + symbol to concatenate two strings together? You can also use the + sym- bol to concatenate a char and a string. What do you think this code fragment prints?
char first, middle, last;
first = 'J';
middle = 'S';
last = 'D';
// a person's initials
System.out.println("Hello, " + first + middle + last + '!');
Here’s the output:
Hello, JSD!
Escape Sequences
Usually, it’s easy to print characters. Just stick them inside a System.out.println statement. But some characters are hard to print. We use escape sequences to print hard-to-print characters such as the tab char- acter. An escape sequence is comprised of a backslash (\) and another character. See Java’s most popular escape sequences in Figure 3.9.
3.20 char Type and Escape Sequences 83
/
numOfClasses