Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

68 HOUR 6:Using Strings to Communicate


The newline character causes the text following the newline character to be
displayed at the beginning of the next line. Look at this example:
System.out.println(“Music by\nMichael Nyman”);

This statement would be displayed like this:
Music by
Michael Nyman

Pasting Strings Together
When youuse System.out.println()and work with strings in other
ways, you can paste two strings together by using +, the same operator
that is used to add numbers.
The +operator has a different meaning in relation to strings. Instead of
performing some math, it pastes two strings together. This action can cause
strings to be displayed together or make one big string out of two smaller
ones.
Concatenationis the word used to describe this action because it means to
link two things together.
The following statement uses the +operator to display a long string:
System.out.println(“\”\’The Piano\’ is as peculiar and haunting as any” +
“ film I’ve seen.\”\n\t— Roger Ebert, Chicago Sun-Times”);

Instead of putting this entire string on a single line, which would make it
harder to understand when you look at the program later, the +operator is
used to break the text over two lines of the program’s Java source code.
When this statement is displayed, it appears as the following:
“‘The Piano’ is as peculiar and haunting as any film I’ve seen.”
— Roger Ebert, Chicago Sun-Times

Several special characters are used in the string: \”, \’, \n, and \t. To bet-
ter familiarize yourself with these characters, compare the output with the
System.out.println()statement that produced it.

Using Other Variables with Strings
Although you can use the +operator to paste two strings together, you use
it more often to link strings andvariables. Take a look at the following:

NOTE
Yo u ’l l p r o b a b l y s e e t h e t e r m
concatenation in other books
as you build your programming
skills,so it’s worth knowing.
However,pasting is the term
used here when one string and
another string are joined togeth-
er. Pasting sounds like fun.
Concatenating sounds like
something that should never be
done in the presence of an
open flame.

Free download pdf