Java Strings: Creation, Concatenation and Immutability (OCP 21)
How Java creates String objects (literals, new, text blocks, valueOf), the three rules of + for concatenation versus addition, char arithmetic traps, null in concatenation, += on strings, and why String immutability means methods return new objects.
kvi5hnuCode Sprout team member7 min readOn this page
Chapter 4 moves from language rules to the core APIs: the classes in java.lang, java.util and java.time that the exam expects you to know method by method. It starts with String, the class that appears in almost every exam question, often as a side detail that decides the answer. This article covers how strings are created, how + decides between adding and joining, and what immutability means in practice. Article 17 covers the String methods, article 18 covers StringBuilder, and article 19 covers ==, equals and the string pool.
Creating a String
A String is an object, a sequence of characters, and a reference type. It's the only class with its own literal syntax:
String a = "Otter"; // literal: comes from the string pool
String b = new String("Otter"); // explicitly creates a new object
String c = """
Otter"""; // text block (article 5): same value as a
String d = String.valueOf(new char[] {'O', 't', 't', 'e', 'r'});
All four hold the same characters. They differ in which object you get. Literals and text blocks are interned and shared, while new always creates a fresh object. That matters for ==, which article 19 covers in detail. For now: compare strings with equals.
String is final (you can't subclass it) and implements CharSequence, Comparable<String> and Serializable (plus Constable and ConstantDesc since Java 12). CharSequence is the read-only interface that String, StringBuilder and StringBuffer share, so a method that takes a CharSequence accepts any of them.
Concatenation: three rules for +
The + operator either adds or concatenates, and a single expression can do both:
- If both operands are numeric (including
char),+means addition. - If either operand is a
String,+means concatenation. - Operators of the same precedence are evaluated left to right, so the decision is made for each
+in turn.
System.out.println(1 + 2); // 3
System.out.println("x" + "y" + 7); // xy7
System.out.println(4 + 5 + "z"); // 9z (4 + 5 first)
System.out.println("z" + 4 + 5); // z45 ("z" + 4 is already a String)
System.out.println("z" + (4 + 5)); // z9 (parentheses first)

When an exam line mixes numbers and strings, go one + at a time and write down the type of the running result. Variables count by their declared type: int five = 5 adds, while String six = "6" concatenates.
char is a number
A char operand doesn't make + concatenate. Only a String does:
System.out.println('a' + 1); // 98 ('a' is 97)
System.out.println('x' + 'y' + "!"); // 241! (120 + 121, then "!")
System.out.println("" + 'a' + 1); // a1 ("" turns it into concatenation)
System.out.println(1 + 'a' + "b"); // 98b
What gets converted, and how
When one operand is a String, the other is converted to text:
- primitives by their standard formatting:
1.0f→"1.0",2L→"2",true→"true",1.0 / 0→"Infinity"; - objects by calling
toString(), so a record printsTicket[animal=lemur, count=2]and an array prints something like[I@1b6d3586; nullbecomes the four letters"null", with no exception:"z" + nullis"znull".
Some expressions don't compile, because + needs a String or numbers on each side:
String s = 1 + 2; // DOES NOT COMPILE: the result is an int
String t = null + null; // DOES NOT COMPILE: bad operand types
boolean f = true + false; // DOES NOT COMPILE
+= with strings
s += x means s = s + x. With a String on the left, anything on the right is concatenated:
var s = "v"; // var infers String
s += 2; // "v2"
s += 'x'; // "v2x"
s += 1.5; // "v2x1.5"
s += false; // "v2x1.5false"
It doesn't work the other way round: int i = 0; i += "a"; fails ("String cannot be converted to int"). No other compound operator works with strings, so s -= "a" doesn't compile.
And if the String on the left is null? String n = null; n += "!"; gives "null!".
Immutability
A String object can never change after it's created. There's no setter, the internal array is private, and the class is final. Every method that seems to modify a string, such as toUpperCase, concat, replace or strip, returns a new String and leaves the original alone:
String name = "lemon";
name.toUpperCase(); // result discarded: name is still "lemon"
String upper = name.toUpperCase(); // "LEMON" in a new object
name = name.concat("s"); // name now refers to a NEW object "lemons"
The exam relies on this constantly. When you see a String method called as a statement by itself, its result is lost.
The variable is not the object. name = name.concat("s") doesn't change the "lemon" object. It points the variable name at a different object. Any other variable that still refers to "lemon" sees "lemon". Making the variable final prevents reassignment, which is a separate question from immutability.
Immutability is what makes it safe to share string literals in the pool, to use strings as HashMap keys, to pass them between threads without locking, and to cache their hash codes. The cost is that building a string in many small steps creates many temporary objects. That's what StringBuilder (article 18) is for.
What's current
- String immutability, the pool and
+concatenation are unchanged through Java 25. - String templates were previewed in Java 21 and 22 and withdrawn in Java 23. Use
+,formattedorString.format.
Exam traps from this article
A complete example
public class Solution {
record Ticket(String animal, int count) {}
public static void main(String[] args) {
System.out.println("-- four ways to get a String --");
String literal = "Otter";
String constructed = new String("Otter");
String block = """
Otter""";
String fromChars = String.valueOf(new char[] {'O', 't', 't', 'e', 'r'});
System.out.println(literal + " " + constructed + " " + block + " " + fromChars);
System.out.println("same text: " + (literal.equals(constructed) && literal.equals(block)
&& literal.equals(fromChars)));
CharSequence seq = literal; // String implements CharSequence
System.out.println("CharSequence length: " + seq.length());
System.out.println("-- + works left to right --");
int five = 5;
String six = "6";
System.out.println(1 + 2 + five + six); // 8 + "6"
System.out.println(six + 1 + 2 + five); // "6" first: all concatenation
System.out.println(six + (1 + 2 + five)); // parentheses force addition
System.out.println('a' + 1); // char + int is int arithmetic
System.out.println("" + 'a' + 1); // a String first changes everything
System.out.println('x' + 'y' + "!"); // 120 + 121, then "!"
System.out.println("-- null and other objects --");
String missing = null;
System.out.println("value: " + missing);
missing += "!"; // null + "!" is "null!"
System.out.println(missing);
System.out.println("ticket: " + new Ticket("lemur", 2));
StringBuilder builder = new StringBuilder("built");
System.out.println("builder: " + builder);
System.out.println("-- += builds a new String each time --");
var s = "v";
s += 2;
s += 'x';
s += 1.5;
s += false;
System.out.println(s);
System.out.println("-- immutability --");
String name = "lemon";
name.toUpperCase(); // result thrown away
System.out.println(name);
String upper = name.toUpperCase();
System.out.println(name + " " + upper);
String original = name;
name = name.concat("s"); // name now points elsewhere
System.out.println(original + " " + name + " " + (original == name));
}
}
Output:
-- four ways to get a String --
Otter Otter Otter Otter
same text: true
CharSequence length: 5
-- + works left to right --
86
6125
68
98
a1
241!
-- null and other objects --
value: null
null!
ticket: Ticket[animal=lemur, count=2]
builder: built
-- += builds a new String each time --
v2x1.5false
-- immutability --
lemon
lemon LEMON
lemon lemons false
Points to notice:
- The four creation styles produce equal values. Whether they are the same object is a separate question (article 19).
six + 1 + 2 + fiveis all concatenation, because the first operand is already aString. Moving the parentheses changes the result.missing += "!"on anullreference produces"null!"without throwing.original == nameisfalseafterconcat: the variable moved to a new object, and the old one is unchanged.
Common questions
Should I ever write new String("…")?
Almost never. It creates a redundant copy of a literal that already exists. It's on the exam to test == versus equals. The new String(char[]) and new String(byte[], charset) constructors are genuinely useful for converting arrays and bytes into strings.
Is concat the same as +?
For two non-null strings, yes. concat accepts only a String and throws NullPointerException if the argument is null, while + accepts anything and turns null into "null".
Why does System.out.println(1 + 2 + "") print 3 but println("" + 1 + 2) print 12?
Left-to-right evaluation. In the first, both + operators see numbers until the last one. In the second, the first + already produces a String.
If strings are immutable, how does s += "x" work?
It builds a new String from the old value plus "x" and assigns it back to s. The old object is unchanged and becomes garbage if nothing else refers to it.
Summary
- Create strings with literals, text blocks,
new String(…)orString.valueOf(…). Compare their contents withequals. +adds when both operands are numeric (charincluded), concatenates when either is aString, and runs left to right.- In concatenation, objects use
toString()andnullbecomes"null". +=on aStringconcatenates anything. No other compound operator works with strings.Stringis immutable andfinal. Its methods return new strings, so an ignored result means no change.
Practice quiz
Test yourself with the strings and concatenation quiz: 10 exam-style questions with explanations.
Previous: Java break, continue, Labels, return and Unreachable Code (OCP 21)
Next: Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)
Related reading
- Java break, continue, Labels, return and Unreachable Code (OCP 21)
- Java while, do/while, for and for-each Loops (OCP 21)
- Java Pattern Matching for switch: Type Patterns, when Guards, null and Record Patterns (OCP 21)
- Java switch Statements and switch Expressions: case Values, yield and Exhaustiveness (OCP 21)
- Java if/else, Pattern Matching for instanceof and Flow Scoping (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.