Previous Section  < Day Day Up >  Next Section

Pasting Strings Together

When you use the System.out.println() statement and handle strings in other ways, you will sometimes want to paste two strings together. You do this by using the same operator that is used to add numbers: +.

The + operator has a different meaning in relation to strings. Instead of trying to do some math, it pastes two strings together. This action can cause strings to be displayed together, or it can make one big string out of two smaller ones.

Concatenation is a word used to describe this action, because it means to link two things together. You'll probably see this term in other books as you build your programming skills, so it's worth knowing. However, pasting is the term used here to describe what happens when one string and another string decide to get together.

Pasting sounds like fun. Concatenating sounds like something that should never be done in the presence of an open flame.

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 up the text over two lines of the program's Java text file. When this statement is displayed, it will appear 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 better familiarize yourself with these characters, compare the output with the System.out.println() statement that produced it.

    Previous Section  < Day Day Up >  Next Section