String literals

suggest change

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

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Literals:
* String literals

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap