4.3. Operations on Strings

There are many kinds of operations that can be performed on strings, but let's start with one you have used already, joining two or more strings together to form a new, combined string. This is often called string concatenation.

4.3.1. Joining Strings

To join two String objects to form a new, single string you use the + operator, just as you have been doing with the argument to the println() method in the program examples thus far. The simplest use of this is to join two strings together:

myString = "The quick brown fox" + " jumps over the lazy dog";

This will join the two strings on the right of the assignment and store the result in the String variable myString. The + operation generates a completely new String object that is separate from the two original String objects that are the operands, and this new object is stored in myString. Of course, you also use the + operator for arithmetic addition, but if either of the operands for the + operator is a String object or literal, then the compiler will interpret the operation as string concatenation and will convert the operand that is not a String object to a string.

Here's an example of concatenation strings referenced by String variables:

String date = "31st ";
String month = "December";
String lastDay = date + month;         // Result is "31st December"

If a String variable that you use as one of the operands to + contains null, then this will automatically be converted to the string "null". So if the

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th 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.