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.

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.

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.

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.

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 ==.

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(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

Common concatenation techniques in Java
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

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.

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.

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().

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
Step 1 — Declare String VariablesWe 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
Step 2 — Concatenate First and Last NameWe 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
Step 3 — Concatenate String with IntegerNow 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
Step 4 — Print the ResultFinally, 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.

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.

Comparison of string concatenation techniques in Java
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
✦ 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.

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.

From today's foundations to tomorrow's skills
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

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.

Practice Problems

PROBLEM 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 + "!";?
PROBLEM 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));
PROBLEM 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.
PROBLEM 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.
PROBLEM 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?

Lesson 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