println with multiple elements

 

For compactness, it’s useful to be able to print out numerical data as well as Strings using the same Java statement.  println makes this possible with the help of the plus operator (the symbol +).  When used in an expression where at least one of the operands is a String, the symbol + signifies that the operands are to be concatenated together (the second is appended to the end of the first one).  For instance, the expression

 

            “miles per gallon: ” + 15

 

combines the String and integer literals into the single String literal

 

            “miles per gallon: 15”

 

This same expression can be supplied to the println statement to produce the last String as output:

 

      System.out.println(“miles per gallon: ” + 15);

 

As we’d expect, we should also be able to construct expressions with multiple operands, so the statement

 

System.out.println(“My car’s fuel efficiency is ” + 35 + “ mpg.”);

 

will generate the output:

 

      My car’s fuel efficiency is 35 mpg.

 

As before, the plus operators are applied from left to right.  This can get us in trouble when we intend to use the plus sign as an arithmetic operator in the same expression.  For instance, the statement

 

System.out.println(“My car’s fuel efficiency is ” + 35 + 5 + “ mpg.”);

 

will output

 

      My car’s fuel efficiency is 355 mpg.

 

The way to understand this is again to think of the expression as a series of subexpressions evaluated from left to right.  After the first one is evaluated, we’re left with

 

            “My car’s fuel efficiency is 35” + 5 + “ mpg.”

 

The next evaluation will append the 5 to the end of the String to produce

 

      “My car’s fuel efficiency is 355”

 

and finally the String literal “ mpg.” is attached to the end. 

 

If we want to have the 35 be added to 5 as a numerical operation, we would need a set of parentheses to force the corresponding plus to be evaluated first:

 

System.out.println(“My car’s fuel efficiency is ” + (35+5) + “ mpg.”);

 

This, of course, will output

 

      My car’s fuel efficiency is 40 mpg.

 

One final minor point.  The use of the plus operator to concatenate elements does not eliminate the rules of operator precedence.  The statement

 

System.out.println(“My car’s fuel efficiency is ” + 35 * 2 + “ mpg.”);

 

will output

 

      My car’s fuel efficiency is 70 mpg.            // I wish

 

since the multiplication is carried out on the two integers before the plus.