Using Other Variables with Strings

Although you can use the + operator to paste two strings together, you 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 minutesRated 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. The System.out.println() statement is being asked to ...

Get Sams Teach Yourself Java™ in 24 Hours, Sixth 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.