Java • Syntax and Core Types

String Creation & Concatenation — Create and concatenate strings

Learn how Java represents text and how you can combine strings to build dynamic output.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

Historical Context & Motivation

Almost every program you have ever used — from social media apps to video games — needs to handle text. Early computers stored characters as raw numbers, and programmers had to manually track where one piece of text ended and the next began. Languages like C required developers to manage memory for character arrays by hand, which led to countless bugs and security flaws. Java was designed from the start to make working with text safer and easier by introducing the String class as a core part of the language.

1972 • C Language & Character Arrays

The C programming language represents text as null-terminated character arrays. Programmers must manually allocate and free memory, making string handling error-prone.

1983 • C++ & std::string

C++ introduces a string class in its standard library, wrapping character arrays inside an object. This reduces some manual memory management but still allows unsafe operations.

1995 • Java 1.0 & the String Class

Java ships with an immutable String class built into java.lang. Strings are first-class objects with automatic memory management and a rich set of built-in methods.

2004 • Java 5 & StringBuilder

Java 5 introduces StringBuilder for efficient string building in loops, complementing the existing StringBuffer with a faster, non-synchronized alternative.

2017 • Java 9 & Compact Strings

Java 9 optimizes internal string storage by using a byte array instead of a char array, cutting memory usage nearly in half for ASCII-only strings.

The central question this lesson addresses is straightforward but essential: How do you create text values in Java, and how do you combine them to produce useful output? Understanding string creation and concatenation is the foundation for everything from printing messages to building file paths and formatting user interfaces.

SECTION 2

Core Principles & Definitions

Before you write your first line of string code, you need to understand a few foundational ideas that make Java strings different from primitive types like int or double. These principles will help you avoid common mistakes and write cleaner code.

1

String Is a Reference Type

A String variable holds a reference (a pointer) to an object in memory, not the text itself. This is unlike primitive types such as int, which store their value directly.
2

Strings Are Immutable

Once a String object is created, its contents cannot be changed. Every operation that appears to modify a string actually creates a brand-new String object in memory.
3

String Literal Pool

Java maintains a special area in memory called the String Pool. When you create a string using double quotes, Java checks the pool first and reuses an existing copy if one matches, saving memory.
4

Concatenation with +

The + operator is overloaded for strings. When at least one operand is a String, Java converts the other operand to a String and joins them together into a new String.
5

The concat() Method

Besides +, Java provides the .concat() method on String objects. It appends one string to the end of another and returns a new String, behaving much like +.
✦

KEY TAKEAWAY

Think of a Java String like a printed poster. Once the poster is printed, you cannot change the letters on it — you would have to print a whole new poster. Similarly, when you concatenate two strings, Java does not modify either original string. Instead, it prints a brand-new poster that contains both messages side by side.

SECTION 3

Visual Explanation — String Creation in Memory

The diagram below illustrates what happens in memory when you create strings using string literals versus the new keyword. Understanding this distinction helps explain why == behaves differently than you might expect when comparing strings.

String Creation: Literal vs new KeywordStack (Variables)s1ref → Pools2ref → Pools3ref → HeapString Pool"Hello"s1 and s2 bothpoint hereHeap (outside pool)"Hello"s3 points here(separate copy)CodeString s1 = "Hello";// literal → stored in String PoolString s2 = "Hello";// literal → reuses same pool objectString s3 = new String("Hello");// new → always creates a fresh object on heaps1 == s2 → trues1 == s3 → falses1.equals(s3) → true
Variables s1 and s2 share the same object in the String Pool because they were created with identical literals. Variable s3 uses new, which always allocates a separate object on the heap, even if the text matches.

Notice that s1 == s2 returns true because both references point to the exact same object in the pool. However, s1 == s3 returns false because s3 points to a different object, even though the text content is identical. This is why you should almost always use .equals() to compare string content, not ==.

SECTION 4

How Concatenation Works Under the Hood

When you write "Hello" + " World", the Java compiler translates that + into a sequence of operations that builds a new String. Since strings are immutable, every concatenation allocates a new object. Understanding the cost of this process helps you write efficient code.

The + Operator Translation

In modern Java (version 9+), the compiler transforms + concatenation into a call to invokedynamic, which the JVM optimizes at runtime. In earlier versions, the compiler would create a StringBuilder behind the scenes. Either way, the principle is the same: the JVM creates a temporary buffer, copies both strings into it, and produces a single new String object.

CONCATENATION COST

Time∝length(s1)+length(s2)Time ∝ length(s₁) + length(s₂)

Each concatenation copies all characters from both strings into a new array. If you concatenate inside a loop with n iterations, the total work grows quadratically: O(n²). Using StringBuilder reduces this to O(n).

Three Ways to Concatenate

TechniqueSyntax ExampleBest For
+ operator"Hi" + " " + nameSimple, one-time concatenations of a few strings
.concat() method"Hi".concat(" ").concat(name)Chaining two strings when you want explicit method calls
StringBuildersb.append("Hi").append(name)Loops or building long strings from many pieces

Common concatenation techniques in Java

Automatic Type Conversion

When you concatenate a non-string value with a String, Java automatically calls String.valueOf() on the non-string operand. For example, "Score: " + 100 converts the integer 100 to the string "100" and then joins them to produce "Score: 100". This automatic type conversion works for all primitive types and objects (via their toString() method).

⚠

Watch Out for Order of Operations

The expression 1 + 2 + " cats" produces "3 cats" because 1 + 2 is evaluated as integer addition first. But "cats " + 1 + 2 produces "cats 12" because once a String is involved, subsequent + operations become string concatenation, evaluated left to right.

SECTION 5

Approaches to String Building

Java gives you several tools for building strings, and choosing the right one depends on the situation. The diagram below compares three common approaches side by side, showing how each handles a loop that builds a greeting from an array of names.

Concatenation in a Loop — Three Approaches❌ Using + in LoopString result = "";for (String n : names){ result = result+n;}Iteration 1"" + "A" → "A" (new obj)Iteration 2"A" + "B" → "AB" (new obj)Iteration 3"AB"+"C" → "ABC" (new obj)Objects Created: nPerformance: O(n²)Slow for large n!✓ Using StringBuilderStringBuilder sb = new StringBuilder();for (String n : names){ sb.append(n);}Iteration 1buffer: [A _ _ _] (same obj)Iteration 2buffer: [A B _ _] (same obj)Iteration 3buffer: [A B C _] (same obj)Objects Created: 1Performance: O(n)Fast and efficient!✓ String.join()String result = String.join(", ", names);Internally usesStringJoiner, whichwraps StringBuilder.// Result:"A, B, C"Objects Created: ~1Performance: O(n)Clean & readable!
Comparison of three approaches to building a string from an array. Using + in a loop creates a new String object on every iteration, leading to O(n²) time. StringBuilder and String.join() both run in O(n) time by reusing a single internal buffer.

For simple cases like System.out.println("Name: " + firstName + " " + lastName), the + operator is perfectly fine and the most readable option. The performance difference only matters when you are concatenating inside a loop that may run hundreds or thousands of times. In those situations, reach for StringBuilder or String.join().

SECTION 6

Worked Example — Building a Greeting Message

Let's trace through a complete example that creates strings, concatenates them, and prints the result. We will build a personalized greeting that includes a user's name and their score on a quiz.

Building a Quiz Result Message

  1. 1

    Step 1 — Declare String Variables

    We start by creating two strings using literals and one integer variable for the score: String firstName = "Alice"; String lastName = "Chen"; int score = 87; Both firstName and lastName point to String objects in the String Pool.
    Three variables created: firstName → "Alice", lastName → "Chen", score → 87
  2. 2

    Step 2 — Concatenate First and Last Name

    We combine them with a space in between: String fullName = firstName + " " + lastName; Java evaluates left to right: first "Alice" + " " produces "Alice ", then "Alice " + "Chen" produces the final result.
    fullName → "Alice Chen"
  3. 3

    Step 3 — Concatenate String with Integer

    Now we build the full message, mixing strings and an integer: String message = "Great job, " + fullName + "! You scored " + score + "/100."; When Java reaches + score, it automatically converts the integer 87 to the String "87" before concatenating.
    message → "Great job, Alice Chen! You scored 87/100."
  4. 4

    Step 4 — Print the Result

    Finally, we output the message: System.out.println(message); This prints the complete string to the console.
    Console output: Great job, Alice Chen! You scored 87/100.
💡

Pro Tip

You can also use String.format() for more readable formatting: String.format("Great job, %s! You scored %d/100.", fullName, score). This approach uses placeholders (%s for strings, %d for integers) and is especially useful when you have many values to insert.

SECTION 7

Strengths & Limitations of Each Approach

Each concatenation technique has trade-offs. The table below summarizes when to reach for each tool, so you can make smart choices in your programs.

TechniqueStrengthsLimitations
+ operatorEasy to read, built into the language, handles automatic type conversionCreates new String objects each time; slow in loops with many iterations
.concat()Explicit and clear; slightly faster than + for two stringsDoes not auto-convert non-string types; throws NullPointerException if called on null
StringBuilderVery fast for building strings in loops; mutable internal buffer avoids creating extra objectsMore verbose syntax; not thread-safe (use StringBuffer if threads are a concern)
String.format()Great readability for complex templates; supports number formatting and paddingSlower than + or StringBuilder; requires learning format specifiers
String.join()Perfect for joining arrays/lists with a delimiter; clean one-linerOnly works with CharSequence types; less flexible for complex patterns

Comparison of string concatenation techniques in Java

✦

KEY TAKEAWAY

Think of choosing a concatenation technique like choosing a tool for a home project. A simple + is like a screwdriver — perfect for hanging a single picture frame. A StringBuilder is like a power drill — overkill for one screw, but essential when you're assembling a bookshelf with dozens of screws. Match the tool to the job.

SECTION 8

Connection to Advanced String Topics

The concepts you have learned here — creating strings and concatenating them — form the foundation for more advanced string manipulation you will encounter as you continue studying Java. Let's preview how these basics connect to topics you may explore next.

What You Learned TodayWhat Comes Next
Creating strings with literals and newString methods like .substring(), .charAt(), .indexOf() for searching and slicing
Comparing with .equals() instead of ==Case-insensitive comparison with .equalsIgnoreCase() and pattern matching with regular expressions
Concatenation with + and StringBuilderText blocks (Java 13+) for multi-line strings and String.format() for template-based output
Immutability of stringsUnderstanding why immutability makes strings safe to share across threads and use as HashMap keys

From today's foundations to tomorrow's skills

As you grow as a programmer, you will also learn about regular expressions, which let you search for patterns in strings (like finding all email addresses in a document), and character encoding (like UTF-8 and Unicode), which determines how characters from every language in the world are stored in memory. For now, the ability to create and concatenate strings gives you the tools to produce meaningful program output, which is the starting point for nearly every application.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why Java strings are called immutable. What happens in memory when you write String s = "Hi"; s = s + "!";?
Show answer
Immutable means the contents of a String object can never be changed after it is created. When you write s = s + "!", Java does not modify the original "Hi" object. Instead, it creates a brand-new String object "Hi!" in memory and updates the variable s to point to this new object. The original "Hi" still exists in the String Pool until the garbage collector reclaims it (if no other reference points to it).

Question 2: BASIC CALCULATION

What does the following code print? Trace through the concatenation step by step. int a = 3; int b = 5; System.out.println("Sum: " + a + b); System.out.println("Sum: " + (a + b));
Show answer
The first line prints Sum: 35. Java evaluates left to right: "Sum: " + 3 produces "Sum: 3", then "Sum: 3" + 5 produces "Sum: 35" (string concatenation, not addition). The second line prints Sum: 8 because the parentheses force (a + b) to be evaluated as integer addition first, yielding 8, which is then concatenated with the string.

Question 3: INTERMEDIATE

Rewrite the following code to use a StringBuilder so it runs efficiently: String result = ""; for (int i = 0; i < 1000; i++) { result = result + i + ", "; } Explain why your version is faster.
Show answer
The efficient version is: StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i).append(", "); } String result = sb.toString(); This is faster because StringBuilder uses a mutable internal character buffer. Instead of creating 1,000 new String objects (one per iteration), it appends characters to the same buffer. The original code runs in O(n²) time because each concatenation copies all previously accumulated characters. The StringBuilder version runs in O(n) time.

Question 4: APPLIED

You are building a simple report card program. Given the arrays below, write code that produces a single String containing each student's name and grade separated by a newline, like "Alice: A\nBob: B+\nCarla: A-". String[] names = {"Alice", "Bob", "Carla"}; String[] grades = {"A", "B+", "A-"}; Use the most appropriate concatenation technique and justify your choice.
Show answer
Since we are building a string in a loop, StringBuilder is the best choice: StringBuilder sb = new StringBuilder(); for (int i = 0; i < names.length; i++) { sb.append(names[i]).append(": ").append(grades[i]); if (i < names.length - 1) sb.append("\n"); } String report = sb.toString(); StringBuilder is the right tool here because we are concatenating inside a loop. Using + would create unnecessary intermediate String objects. The if-statement avoids adding a trailing newline after the last entry.

Question 5: CRITICAL THINKING

Consider the following two code snippets. Predict whether result1 == result2 evaluates to true or false. Explain your reasoning using what you know about the String Pool and immutability. String result1 = "Hello" + " World"; String result2 = "Hello World"; Now consider a variation: String part = " World"; String result3 = "Hello" + part; Does result2 == result3 evaluate to true or false? Why?
Show answer
result1 == result2 evaluates to true. The Java compiler can evaluate "Hello" + " World" at compile time because both operands are compile-time constants (literals). The compiler folds them into the single literal "Hello World", which is then placed in the String Pool. Since result2 is also the literal "Hello World", both variables point to the same pooled object. However, result2 == result3 evaluates to false. The variable part is not a compile-time constant — it is a variable that could theoretically change. So the compiler cannot fold "Hello" + part at compile time. The concatenation happens at runtime, creating a new String object on the heap that is not in the pool. To make them equal by reference, you would need to declare part as final, making it a compile-time constant.

SUMMARY

Lesson Summary

Summary

In Java, a String is a reference type that represents a sequence of characters. You can create strings using string literals (double-quoted text stored in the String Pool) or the new keyword (which always creates a separate object on the heap). Strings are immutable — once created, their contents cannot be changed. Every apparent modification produces a new String object.

To combine strings, you can use the + operator for simple cases, the .concat() method for explicit method-style joining, or StringBuilder for efficient concatenation inside loops. The + operator automatically converts non-string values like integers to strings, but be mindful of left-to-right evaluation order — use parentheses when you need arithmetic before concatenation. Always compare string contents with .equals(), never with ==.

Varsity Tutors • Java • String Creation & Concatenation