liveBook · Manning

String literal

As explained in 100 Java Mistakes and How to Avoid Them

A string literal is a Java source-code literal representing a sequence of characters using double quotation marks.

A string literal is a Java source-code literal representing characters inside double quotation marks. It can contain escape sequences such as "\\b" and "\\t", but backslashes require particular care in regular expressions. section 6.11

Prefer a string literal when an API expects text. A character literal can select a numeric overload instead: passing '[' to StringBuilder chooses the int-capacity constructor, using character value 91, rather than appending an opening bracket. section 9.1

Character literal versus string literal

The risky form is `new StringBuilder('[')`. Use `new StringBuilder("[")`, or construct the builder and append the string literal separately. The performance penalty is described as marginal, while the string form cannot be implicitly converted to a number. section 9.1

A one-character string literal can also prevent accidental unary-plus behavior. In `"User not found: " + + '"'`, the character literal is exposed to a confusing expression pattern; replacing it with `"\""` makes arithmetic misuse a compilation error. section 2.5

StringBuilder sb = new StringBuilder('[');    #1
sb.append(value);
sb.append(']');

Inspect the constructor call that passes a character literal and widens it to an integer capacity. section 9.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains escapes and two practical failure modes, stopping short of a complete syntax treatment.
Examples
Uses StringBuilder brackets, an error message, escape sequences, regular expressions, and format strings as cautionary examples.
What it assumes
Assumes Java expressions, overloads, character literals, and basic string APIs; teaches the relevant literal distinction through failures.
What you can do after
Apply string literals to avoid numeric overload selection and unary-plus confusion, while reviewing escapes and regex-sensitive APIs carefully.
How it connects
Connects string literals with character literals, overloaded constructors, unary plus, regular expressions, and static analysis.

Also explained in

Compare how 2 books explain string literal →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.