Using Other Variables with Strings

Although you can use the + operator to paste two strings together, as demonstrated in the preceding section, you will use it more often to link strings and variables. Take a look at the following:

int length = 121;
char rating = 'R';
System.out.println("Running time: " + length + " minutes");
System.out.println("Rated " + rating);

This code will be displayed as the following:

Running time: 121 minutes
Rated R

This example displays a unique facet about how the + operator works with strings. It can cause variables that are not strings to be treated just like strings when they are displayed. The variable length is an integer set to the value 121. It is displayed between the strings Running time: and minutes ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.