Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

String Arithmetic

As stated earlier today, the + operator has a double life outside the world of mathematics. It can be used to concatenate two or more strings.

New Term

Concatenate means to link two things together. For reasons unknown, it is the verb of choice when describing the act of combining two strings—winning out over paste, glue, affix, combine, link, and conjoin.

In several examples, you have seen statements that look something like this:

String firstName = "Raymond";
System.out.println("Everybody loves " + firstName);

These two lines result in the following text being displayed:

Everybody loves Raymond

The + operator combines strings, other objects, and variables to form a single string. In the preceding example, the literal Everybody loves is concatenated to the value of the String object firstName.

Working with the concatenation operator is easy in Java because of the way it can handle any variable type and object value as if it were a string. If any part of a concatenation operation is a String or String literal, all elements of the operation will be treated as if they were strings:

System.out.println(4 + " score and " + 7 + " years ago.");

This produces the output text 4 score and 7 years ago., as if the integer literals 4 and 7 were strings.

There also is a shorthand += operator to add something to the end of a string. For example, consider the following expression:

myName += " Jr.";

This expression is equivalent to the following:

myName = myName + " Jr.";

In this example, it changes the value of myName (which might be something like Efrem Zimbalist) by adding Jr. at the end (Efrem Zimbalist Jr.).

  • + Share This
  • 🔖 Save To Your Account