A Java String represents a sequence of text. String literals use double quotes, concatenation combines text, and escape sequences let a literal contain characters that would otherwise interfere with Java syntax. These basics are useful for messages, filenames and reports, but they also affect calculations when numbers appear beside text.
Strings are immutable: an operation that appears to change a string actually creates or selects another value rather than altering the original string object. Keep that distinction in mind when you combine text or call a method such as toUpperCase.
Create text with string literals
A string literal such as "Hello" supplies a String value. Double quotes mark the literal’s boundaries; they are not part of the stored text. An empty string, "", is valid and contains no code units. It differs from null, which means a reference does not point to a String object. Calling a method on a null reference fails, while calling length on an empty string returns zero.
Use String when a value can contain several characters. A char literal uses single quotes and represents one UTF-16 code unit. "A" and 'A' therefore have different types despite displaying similarly. Unicode characters can be written directly in UTF-8 source files when the compiler encoding matches the file; escaped forms are useful when the character would be invisible or syntactically special.
Concatenate labels and values
The + operator concatenates when a string participates. In "Room " + 12, Java converts the integer to its text representation and creates Room 12. The original integer variable, if any, remains numeric. Add spaces and punctuation explicitly: Java does not insert a space between concatenated parts.
Chains of + are evaluated according to their grouping. The expression 2 + 3 + " seats" begins with numeric addition and produces 5 seats. The expression "Seats: " + 2 + 3 begins with string concatenation and produces Seats: 23. Parentheses around 2 + 3 make the numeric intention clear. For a long loop building many pieces, consider StringBuilder rather than repeatedly appending to an immutable String.
Escape characters inside a literal
A backslash introduces an escape sequence. Use \" to include a double quote, \\ to include a backslash, \n for a newline and \t for a tab. These sequences are interpreted when Java reads the string literal. The backslash is not separately displayed unless you escape it.
For example, a source literal "She said \"Hello\"." stores the quotation marks around Hello. A Windows-style path needs escaped backslashes in an ordinary literal, such as "C:\\notes\\draft.txt". Prefer Path APIs for actual filesystem work because separators and resolution rules vary by environment. A tab inserts a tab character, not a guaranteed number of spaces; its displayed alignment depends on the console’s tab stops. Use formatting when fixed columns matter.
Immutability and comparing content
Assigning a new value to a String variable changes the reference held by that variable. It does not modify the previous String object. Methods such as trim, replace and toUpperCase return a result; if you ignore that returned value, your original variable remains unchanged.
Use equals to compare text content. The == operator compares references and can be misleading because some literals are shared through interning. A test using literals might appear to work with == and later fail for input read at runtime. For a known literal, "yes".equals(answer) safely returns false when answer is null. If both values can be null, Objects.equals provides a null-safe comparison. Decide whether case sensitivity belongs to the application before selecting equalsIgnoreCase.
Text blocks for multiline text
Java text blocks use three double quotes and are available as a permanent language feature from Java 15. The opening delimiter must be followed by a line terminator. A text block improves the readability of multiline content, such as a short message or a sample document, without concatenating many quoted lines.
Text blocks still process escape sequences and adjust incidental indentation. The placement of the closing delimiter affects whether a trailing newline remains. Do not assume the displayed indentation exactly matches all source indentation: the language removes common incidental leading spaces. Inspect the actual output when whitespace matters. Text blocks are not templates that automatically substitute variables; use an explicit formatting or concatenation operation when text needs dynamic values.
Practice with explained solutions
Task 1. Build the message Total: 12 from integer values 7 and 5 so addition occurs first.
Solution. Use "Total: " + (7 + 5), or calculate the sum in a variable before concatenation.
Task 2. Explain the difference between an empty string and a null String reference.
Solution. The empty string is a real object value with length zero. A null reference has no String object, so calling length through it throws an exception.
Java Summary
- String methods return results rather than changing the original immutable object.
- Use equals for text content and escape quotes or backslashes inside ordinary literals.
- Calculate a numeric total before concatenating it with a label.
- Continue with string methods.
Java Examples
Each example shows the code, the output it produces and what each part does.
Keep arithmetic separate from text
Save this complete program as StringTotals.java. Compile with javac --release 17 StringTotals.java and run with java StringTotals.
public class StringTotals {
public static void main(String[] args) {
int adults = 2;
int children = 3;
System.out.println("Visitors: " + adults + children);
System.out.println("Visitors: " + (adults + children));
}
}Visitors: 23
Visitors: 5Line-by-line explanation
- Lines 1 to 8The first line turns the label and adults into a string before appending children. The second line calculates the sum inside parentheses, then appends five. Both compile, so the wrong answer would be a logic error rather than a syntax error. Computing int visitors = adults + children first is another readable option when the total is used elsewhere.
Display quotes and backslashes
Save this complete program as EscapedMessage.java. Compile with javac --release 17 EscapedMessage.java and run with java EscapedMessage.
public class EscapedMessage {
public static void main(String[] args) {
System.out.println("Status: \"Ready\"");
System.out.println("C:\\notes\\draft.txt");
System.out.println("First\nSecond");
}
}Status: "Ready"
C:\notes\draft.txt
First
SecondLine-by-line explanation
- Lines 1 to 7Escaped double quotes become quotation marks in the output, while each escaped backslash becomes one backslash. The newline escape splits the final string over two displayed lines, even though it is supplied to a single println call. This example displays a path only; it does not create or open that file. Distinguish producing text from performing a filesystem operation.
Capture an immutable operation’s result
Save this complete program as StringReplacement.java. Compile with javac --release 17 StringReplacement.java and run with java StringReplacement.
public class StringReplacement {
public static void main(String[] args) {
String original = "red kite";
String changed = original.replace("red", "blue");
System.out.println(original);
System.out.println(changed);
System.out.println("blue kite".equals(changed));
}
}red kite
blue kite
trueLine-by-line explanation
- Lines 1 to 9replace returns the revised text and the assignment stores it in changed. original still refers to red kite, demonstrating immutability. The equals call compares characters and returns true. If the replace call had been written without assigning or otherwise using its result, no variable would contain the revised text.
Common Java Mistakes
Comparing string content with ==
Do not use == to test ordinary string content. Sharing a literal can hide the problem in a tiny example, so test values obtained through different routes as well. Also avoid assuming that a visible backslash in a requirement can be copied directly into a Java literal: it may begin an escape sequence and need its own escaping.
Java FAQ
Does concatenation change a number’s type permanently?
No. Java uses a textual representation in the resulting string; a numeric variable keeps its declared type and value.
Are text blocks available in Java 17?
Yes. They are supported without preview flags, although their whitespace rules still deserve attention when exact output matters.
Is string concatenation with + slow in Java?
For a single expression such as "Hi " + name + "!", no: the compiler generates efficient code for it. Repeated concatenation inside a loop is different, because every pass creates a new String. Use a StringBuilder or String.join when building text from many pieces.
How do I write a Windows file path in a Java string?
Each backslash must be escaped, so C:\data\report.txt is written "C:\\data\\report.txt". Java also accepts forward slashes on Windows, and Path.of("C:", "data", "report.txt") avoids separators altogether, which is the cleanest choice for file code.
What happens to indentation in a text block?
Java removes the incidental indentation shared by all lines, measured from the least-indented line, including the closing """. Moving the closing delimiter further left keeps more spaces at the start of each line. Trailing spaces on each line are also removed unless you escape them.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What remains in original after original.replace is called without storing its result?
Which ordinary literal displays one backslash?
Java Quiz
2 questions to check what you learned.
Which method compares String content?
- equals
- == in every situation
- A numeric cast
What does "Count: " + 2 + 3 produce?
- Count: 23
- Count: 5
- A compilation error