Java Strings

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Basics

What You’ll Learn

Strings hold almost every piece of text in Java—user names, error messages, JSON data, and file paths. This guide teaches how to create strings, understand immutability, join text, compare safely, and use essential String methods.

01

String Basics

Text in Java.

02

Immutability

Strings don’t change.

03

Concatenation

Join with +

04

Common Methods

length, charAt, equals.

05

Search & Format

contains, format.

06

Method Index

15 full tutorials.

Definition and Usage

In Java, a String is an object of the java.lang.String class. It represents a sequence of characters used to store and manipulate text. You assign strings to variables, pass them to methods, and print them with System.out.println().

The String class provides dozens of instance methods for reading characters, comparing text, searching substrings, and formatting output. A few helpers such as String.format() and String.copyValueOf() are static and are called on the class name.

💡
Beginner Tip

Compare string content with equals(), not ==. The == operator checks whether two variables refer to the same object in memory—two strings with identical text can still be different objects.

📝 Syntax

Java offers several ways to create and work with strings:

Java
String literal = "Hello, Java!";     // double-quoted literal
String built   = first + " " + last;  // + concatenation
int len        = text.length();       // instance method
char ch        = text.charAt(0);      // read character at index
boolean same   = text.equals("Hi");   // compare content

Creating Strings

  • String literals ("...") — the most common form; stored in the string pool for efficiency.
  • new String(...) — creates a new object explicitly; rarely needed for everyday code.
  • Text blocks ("""...""") — multi-line strings (Java 15+); great for SQL snippets and JSON templates.

Calling String Methods

Most methods use dot notation on a String variable:

name.length()
name.toUpperCase()
name.contains("Java")
String.format("Hi, %s", name)

⚡ Quick Reference

Create
String s = "Hello, Java!";

String literal

Concatenate
String full = a + " " + b;

+ operator

Length
text.length()

Number of char units

Compare text
str1.equals(str2)

Content equality

Examples Gallery

Work through these five examples from basic string creation to comparison and search patterns used in real Java programs.

📚 Getting Started

Create your first strings and display them in the console.

Example 1 — Create and Display Strings

Assign text to variables and print them—the foundation of every Java program.

Java
public class StringsIntro {
    public static void main(String[] args) {
        String language = "Java";
        int version = 21;

        System.out.println("Language: " + language);
        System.out.println("Version: " + version);
        System.out.println("Ready to learn strings!");
    }
}

How It Works

The + operator joins a string and a number; Java converts the number to text automatically. System.out.println() prints each line and adds a newline.

Example 2 — String Literals and Escape Sequences

See how quotes, backslashes, and special characters are written inside strings.

Java
public class StringLiterals {
    public static void main(String[] args) {
        String quote = "She said, \"Hello!\"";
        String path  = "C:\\Users\\Dev\\project";
        String lines = "Line 1\nLine 2";

        System.out.println(quote);
        System.out.println(path);
        System.out.println(lines);
    }
}

How It Works

Use \" for a double quote inside a string and \\ for a backslash. \n inserts a newline. Unlike some languages, Java has no single-quoted string type—character literals use single quotes: 'A'.

📈 Practical Patterns

Concatenation, inspection, comparison, and search.

Example 3 — Concatenation with + and concat()

Build messages by joining strings with the + operator or the concat() method.

Java
public class StringConcat {
    public static void main(String[] args) {
        String first = "Hello";
        String last  = "Java";

        String greeting = first + ", " + last + "!";
        System.out.println(greeting);

        String status = "Status: ";
        status = status.concat("Active");
        System.out.println(status);
    }
}

How It Works

Because strings are immutable, concat() returns a new string—you must assign the result. The + operator is shorter for small joins; use StringBuilder when building long text inside loops.

Example 4 — length(), charAt(), and equals()

Inspect strings and compare content safely—three methods every Java beginner should know.

Java
public class StringMethods {
    public static void main(String[] args) {
        String word = "Hello";

        System.out.println("Length: " + word.length());
        System.out.println("First char: " + word.charAt(0));
        System.out.println("Last char: " + word.charAt(word.length() - 1));

        String copy = new String("Hello");
        System.out.println("equals(): " + word.equals(copy));
        System.out.println("== : " + (word == copy));
    }
}

How It Works

charAt() uses zero-based indexing—the first character is at index 0. equals() returns true because both strings contain “Hello”, but == is false because word is a literal and copy is a separate object created with new.

🚀 Common Use Cases

  • User input — read names, emails, and commands from the console or web forms.
  • Validation — check file extensions with endsWith(), search paths with contains().
  • Display output — build messages with + or String.format() for readable reports.
  • Password checks — compare typed passwords with equals(), never with ==.
  • Sorting text — order names or labels with compareTo() (case-sensitive lexicographic order).
  • File I/O — convert strings to bytes with getBytes() before writing to files or networks.

🧠 How Java Strings Work

1

You create a String

Write a literal "Hello", read input, or build text with concatenation and format templates.

Create
2

Java stores immutable text

The String object holds a fixed character sequence. Any “change” produces a new String.

Immutable
3

Methods read or transform

Call length(), charAt(), equals(), contains(), and dozens more on the object.

Methods
=

Result or output

Print to the console, return from a method, save to a file, or pass to the next step in your program.

📝 Notes

  • Strings are immutable—assign the return value of methods like toUpperCase() and trim().
  • Use equals() for content comparison; use == only when you need reference identity.
  • Guard against null: call "expected".equals(variable) when variable may be null.
  • length() counts UTF-16 code units; emoji and some symbols may use two units (see code-point tutorials).
  • Prefer StringBuilder over repeated + in loops for better performance.
  • String methods are called with dot notation—text.length()—not as standalone functions like in PHP.

Conclusion

Strings are the backbone of Java text handling. Master literals, immutability, concatenation, and a handful of essential methods like length(), charAt(), equals(), and contains()—and you are ready to write real programs that read, compare, and display text.

Practice the examples on this page, then explore the full String Methods index for in-depth tutorials on every method in our series.

💡 Best Practices

✅ Do

  • Compare text with equals() or equalsIgnoreCase()
  • Use contains() and endsWith() for simple validation
  • Assign results from trim(), toUpperCase(), etc.
  • Use String.format() for readable formatted output
  • Use StringBuilder when concatenating in loops

❌ Don’t

  • Compare string content with ==
  • Call instance methods on a possibly null reference
  • Assume length() equals visible character count for all Unicode
  • Build long strings with + inside tight loops
  • Forget that strings never change—methods return new objects

Key Takeaways

Knowledge Unlocked

Five things to remember about Java strings

Use these points as you write your first Java programs.

5
Core concepts
🔒 02

Immutable

Methods return new text.

Concept
🔗 03

Join with +

Concatenate strings.

Operator
🛠 04

equals() not ==

Compare content safely.

Methods
📚 05

Method Index

15 full tutorials.

Next step

❓ Frequently Asked Questions

A String is an object of the java.lang.String class that stores a sequence of characters—names, messages, file paths, and more. You create strings with double-quoted literals like "Hello" or with the new keyword. String is one of the most used types in Java programs.
Strings are immutable. Once created, their character sequence cannot change. Methods like toUpperCase(), concat(), and replace() return new String objects. For frequent edits in loops, use StringBuilder or StringBuffer instead.
equals() compares character content—use it to check whether two strings have the same text. == compares object references (same object in memory). Always use equals() for text comparison; == can be true only when both variables refer to the exact same String instance.
Use the + operator: String full = first + " " + last;. You can also call concat(): greeting.concat(", Java!"). For many pieces in a loop, StringBuilder is faster than repeated + concatenation.
length() returns the number of char code units in the string—the same index range used by charAt(). It counts UTF-16 code units, not always visible Unicode characters (emoji may use two code units). For full Unicode character counts, see codePointCount() in the method tutorials.
Learn how to create strings and print them, then practice length(), charAt(), equals(), and contains(). When you are comfortable with the basics on this page, open the String Methods index for full guides on every essential java.lang.String method.
Did you know?

Java string literals like "Hello" are stored in a string pool. When you write String a = "Hi"; String b = "Hi";, both variables may refer to the same pooled object—which is why == sometimes appears to work for literals but is still unsafe for comparing text in general.

Explore every String method

Open the method index for searchable guides with syntax, five examples, and FAQs for each method.

String Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful