Page 474 - Introduction to Programming with Java: A Problem Solving Approach
P. 474
440 Chapter 11 Type Details and Alternate Coding Mechanisms
The ASCII character set served well in the early years of computer programming, but it’s no longer sufficient. Sometimes you’ll need characters and symbols that are outside of the ASCII character set. For ex- ample, suppose you want to display a check mark (√) or the pi symbol (π). Those two characters don’t appear in Figure 11.4. Those characters are part of a newer coding scheme called Unicode, which is a superset of ASCII. You can learn about Unicode in the optional section at the end of this chapter (Section 11.13). In that section, we show you how to access the check mark and pi symbols and the many other characters enumer- ated in the Unicode standard.
Using the + Operator with chars
Remember how you can use the + operator to concatenate two strings together? You can also use the + op-
erator to concatenate a char to a string. Note this example: char first = 'J’;
char last = 'D';
System.out.println("Hello, " + first + last + '!');
Output:
Hello, JD!
When the JVM sees a string next to a sign, it concatenates by first converting the operand on the other
side of the sign to a string. So in the above example, the JVM converts the first variable to a string and
then concatenates the resulting “J” to the end of “Hello, ” to form “Hello, J”. The JVM does the same thing
with each of the next two characters it sees, last’s stored character and ‘!’. It converts each one to a string Apago PDF Enhancer
and concatenates each one to the string at its left.
Be aware that if you apply the + operator to two characters, the + operator does not perform concatena-
tion; instead, it performs mathematical addition using the characters’ underlying ASCII values. Note this example:
char first = 'J';
char last = 'D';
System.out.println(first + last + ", What's up?");
Output:
142, What’s up?
Theintendedoutputis:JD, What’s up?Whydoesthecodefragmentprint142insteadofJD?TheJVM evaluates + operators (and most other operators as well) left to right, so in evaluating println’s argument, itfirstevaluatesfirst + last.Sincebothfirstandlastarecharvariables,theJVMperforms mathematical addition using the characters’ underlying ASCII values. first holds ‘J’ and J’s value is 74. lastholds‘D’andD’svalueis68.Sofirst + lastevaluatesto142.
There are two ways to fix the above code. You can change the first two lines to string initializations like this:
String first = "J";
String last = "D";
Or you can insert an empty string at the left of println’s argument like this: System.out.println("" + first + last + ", What’s up?");