Concatenating Strings

Combine two strings by using the plus sign (+) as a concatenation operator:

String hello = “Hello, “;

String world = “World!”;

String greeting = hello + world;

The final value of the greeting variable is “Hello, World!”

tip.eps When Java concatenates strings, it doesn’t insert any blank spaces between the strings. Thus, if you want to combine two strings and have a space appear between them, make sure that the first string ends with a space or that the second string begins with a space. (In the preceding example, the first string ends with a space.)

You can concatenate a string literal (one or more text characters enclosed in quotation marks) along with the string variables:

String hello = “Hello”;

String world = “World!”;

String greeting = hello + “, “ + world;

Java automatically converts primitive data types to string values if you concatenate a primitive data type with a string. For example:

String msg = “The value of i is “ + i;

Get Java For Dummies Quick Reference 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.