Fundamentals 12 min read

How to Create, Manipulate, and Compare Java Strings Effectively

This article explains Java's immutable String class, covering three ways to instantiate strings, methods for length, concatenation (concat and +), character access, substring extraction, splitting, replacing, searching, and comparison using equals versus ==, with concrete code examples and key rules for each operation.

Lisa Notes
Lisa Notes
Lisa Notes
How to Create, Manipulate, and Compare Java Strings Effectively

String Class Overview

The Java String class encapsulates character sequences and is immutable: once created, its content cannot be changed; any modification returns a new String object.

Creating String Objects

Three initialization forms are demonstrated:

Using new operator: String teacher_name = new String("王老师"); or creating an empty string with new String("") or new String().

Direct literal assignment: String teacher_name = "王老师"; Assigning null when the initial value is unknown:

String teacher_name = null; // later teacher_name = "王老师";

Note that an empty string ( "") is a valid String object of length 0, while null denotes no object reference and will cause NullPointerException if accessed.

Getting String Length

The length() method returns the number of characters, including spaces and punctuation. Example:

String str = "大家好,我是王老师!";
int len = str.length(); // len = 10

Another example shows that spaces and punctuation are counted:

String str = "Hello,my name is Tom! ";
int len = str.length(); // len = 21

String Concatenation

Two approaches are shown:

Using concat() method:

String s1 = "Hello, ";
String s2 = "my name is Tom!";
String s3 = s1.concat(s2);
System.out.println(s3); // Hello, my name is Tom!

Using the + operator, which is more flexible and also supports mixed-type concatenation:

String name = "王老师";
int age = 38;
System.out.println(name + "的年龄是" + age); // 王老师的年龄是38

The evaluation order follows left‑to‑right rules, and when one operand is a String, the + operator performs concatenation.

Character and Substring Access

Access a single character with charAt(int index) (index starts at 0). Example:

String s1 = "Java programming! ";
char subCh = s1.charAt(7); // 'o'

Extract a substring with substring(int beginIndex, int endIndex), which follows a left‑closed, right‑open interval ( endIndex not included). Example extracts characters 8‑12 (excluding 12):

String str = "Hello, world!";
String sub = str.substring(8, 12); // "world"

String ↔ Char Array Conversion

Convert a char[] to a String using the constructor:

char[] array = {'w','o','r','l','d'};
String s1 = new String(array);
System.out.println(s1); // world

Convert a String to a char[] with toCharArray() (example output shown as individual characters).

Common String Operations

Splitting with split(regex) (first argument is a regular expression).

Replacing with replaceAll(regex, replacement) (regex must be escaped for special symbols).

Searching with indexOf (left‑to‑right) and lastIndexOf (right‑to‑left); both return -1 if not found. contains internally uses indexOf.

String Comparison

Two primary methods: == compares object references (memory addresses). Literal strings may share the same pool, yielding true; new String() creates distinct objects, yielding false. equals() compares the actual character content and returns true when the texts match; it is recommended for business code.

Core Rules Summary

All modification methods return a new String; the original remains unchanged.

Indices start at 0; the last index equals str.length() - 1. substring(a,b) follows left‑closed, right‑open interval.

Methods that accept a regex (e.g., split, replaceAll) require proper escaping of special characters.

Prefer equals() for content comparison; avoid == unless reference equality is intended.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaStringComparisonImmutableSubstringConcatenation
Lisa Notes
Written by

Lisa Notes

Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.