Java Language String literals


Example

String literals provide the most convenient way to represent string values in Java source code. A String literal consists of:

  • An opening double-quote (") character.
  • Zero or more other characters that are neither a double-quote or a line-break character. (A backslash (\) character alters the meaning of subsequent characters; see Escape sequences in literals.)
  • A closing double-quote character.

For example:

"Hello world"   // A literal denoting an 11 character String
""              // A literal denoting an empty (zero length) String
"\""            // A literal denoting a String consisting of one 
                //     double quote character
"1\t2\t3\n"     // Another literal with escape sequences

Note that a single string literal may not span multiple source code lines. It is a compilation error for a line-break (or the end of the source file) to occur before a literal's closing double-quote. For example:

"Jello world    // Compilation error (at the end of the line!)

Long strings

If you need a string that is too long to fit on a line, the conventional way to express it is to split it into multiple literals and use the concatenation operator (+) to join the pieces. For example

String typingPractice = "The quick brown fox " +
                        "jumped over " +
                        "the lazy dog"

An expression like the above consisting of string literals and + satisfies the requirements to be a Constant Expression. That means that the expression will be evaluated by the compiler and represented at runtime by a single String object.

Interning of string literals

When class file containing string literals is loaded by the JVM, the corresponding String objects are interned by the runtime system. This means that a string literal used in multiple classes occupies no more space than if it was used in one class.

For more information on interning and the string pool, refer to the String pool and heap storage example in the Strings topic.