Sub topic 9
Strings and String Manipulation
A string is a piece of text, like "Hello" or "Jane Doe". In Java, strings are so common that the language gives them special treatment. This chapter explains what a String really is, how to create one, and how to use the most useful built-in methods (a method is a named action an object can perform) to work with text.
What you need first: you should know how to declare variables and call methods like System.out.println(). You do not need experience with classes and objects yet — this chapter introduces just enough of that idea to make sense of strings.
Strings Are Objects
In the previous chapters you met primitive types like int and double. A primitive holds a simple value directly. A String is different: it is an object, a bundle of data plus actions (methods) that work on that data.
That difference matters because objects come with built-in methods. An int can only hold a number. A String can tell you its length, hand you its characters one at a time, convert itself to upper case, and much more.
Here is the simplest way to make a string:
String greeting = "Hello";
System.out.println(greeting);The text between the double quotes is called a string literal — a literal value written directly in the code. Java sees "Hello" and creates a String object containing those five characters.
Immutability: Strings Never Change
Here is the single most important fact about Java strings: they are immutable, meaning they cannot be changed after they are created.
When you "modify" a string, Java does not edit the original. Instead, every string method that seems to change text actually returns a new string, leaving the original untouched:
String name = "ada";
String upper = name.toUpperCase();
System.out.println(name); // ada (unchanged!)
System.out.println(upper); // ADA (a brand-new string)A common beginner mistake is calling a method and throwing the result away:
String word = "hello";
word.toUpperCase(); // result discarded
System.out.println(word); // still "hello"Getting Information About a String
The most-used string methods fall into a few groups. The first group answers questions about the string.
String text = "Java Basics";
System.out.println(text.length()); // 11
System.out.println(text.isEmpty()); // false
System.out.println(text.isBlank()); // false (" " spaces count as blank)
System.out.println(text.charAt(0)); // 'J'length()returns the number of characters.isEmpty()returnstrueonly for a string with zero characters ("").isBlank()returnstruefor empty strings and strings made only of spaces.charAt(index)returns the character at a given position. Indexing starts at 0, so position 0 is the first character.
Searching Inside a String
The second group finds where text appears.
String sentence = "the quick brown fox";
System.out.println(sentence.indexOf("quick")); // 4
System.out.println(sentence.indexOf("cat")); // -1 (not found)
System.out.println(sentence.contains("fox")); // true
System.out.println(sentence.startsWith("the")); // true
System.out.println(sentence.endsWith("fox")); // trueindexOf returns the starting index of the first match, or -1 if the text is not there. Checking for -1 is a classic way to test whether a string contains something.
Changing and Cleaning Up a String
The third group produces new, transformed strings.
String messy = " Hello World ";
System.out.println(messy.trim()); // "Hello World"
System.out.println(messy.replace("l", "L")); // " HeLLo WorLd "
System.out.println("hi".toUpperCase()); // "HI"
System.out.println("HI".toLowerCase()); // "hi"trim() removes spaces (and similar whitespace) from both ends — very handy when cleaning up user input. replace(old, new) swaps every occurrence of one piece of text for another.
Slicing: substring
To pull out part of a string, use substring(beginIndex, endIndex). It takes characters starting at beginIndex and stops just before endIndex:
String word = "programming";
System.out.println(word.substring(0, 3)); // pro
System.out.println(word.substring(3)); // ramming (to the end)The rule to remember: the character at endIndex is not included. The length of the result is endIndex - beginIndex.
Comparing Strings: Theequals Trap
This is the mistake almost every Java beginner makes. There are two ways to compare strings, and only one of them is correct.
The == operator compares references — roughly, whether two variables point to the same object in memory. The equals() method compares the actual characters:
String a = "cat";
String b = new String("cat");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same characters)If you want to compare while ignoring upper and lower case, use equalsIgnoreCase:
System.out.println("YES".equalsIgnoreCase("yes")); // trueBuilding Strings from Pieces: Concatenation and Joining
Concatenation means joining strings end to end. The + operator does this, and it also converts numbers automatically:
String name = "Ada";
int age = 36;
System.out.println(name + " is " + age + " years old");
// Ada is 36 years oldWatch out: + means addition if both sides are numbers, and concatenation if either side is a string:
System.out.println(1 + 2); // 3 (numbers)
System.out.println("1" + 2); // 12 (string plus number)
System.out.println(1 + 2 + "a"); // "3a" (adds first, then joins)When you build a long string in a loop, creating a new string every time is wasteful. Java provides StringBuilder, a mutable (changeable) text holder built for this job:
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append("line ").append(i).append("\n");
}
System.out.print(sb.toString());append() adds text to the builder, and toString() turns the finished contents into a normal String. For a beginner, + is fine for small cases; reach for StringBuilder when joining many pieces, especially inside a loop.
Converting Between Strings and Numbers
User input and text files always give you strings, but you often need numbers:
String numberText = "42";
int n = Integer.parseInt(numberText); // String -> int
String back = String.valueOf(n); // int -> String
System.out.println(n + 1); // 43 (real math)
System.out.println(back + 1); // 421 (text joined together)Integer.parseInt throws a NumberFormatException if the text is not a valid number — for example, "4a2".
Splitting a String into Pieces
split() cuts a string into an array (a numbered list of values) using a separator:
String csv = "red,green,blue";
String[] colors = csv.split(",");
for (String c : colors) {
System.out.println(c);
}
// red
// green
// blueThe separator is interpreted as a small pattern language called a regular expression. For simple separators like "," or " " this does not matter, but be aware that some characters (like . and |) have special meaning and must be escaped, e.g. split("\\.").
Putting It Together: A Small Worked Example
Here is a program that cleans up and checks a username, using several methods together:
public class NameCheck {
public static void main(String[] args) {
String input = " Ada Lovelace ";
String name = input.trim(); // remove outer spaces
if (name.isEmpty()) {
System.out.println("Name is required.");
} else if (name.contains("@")) {
System.out.println("Name cannot contain '@'.");
} else {
String first = name.substring(0, name.indexOf(" "));
String initial = String.valueOf(first.charAt(0)).toUpperCase();
System.out.println("Welcome, " + name.toUpperCase());
System.out.println("First name: " + first);
System.out.println("Initial: " + initial);
}
}
}Output:
// Welcome, ADA LOVELACE
// First name: Ada
// Initial: AThe flow of that program looks like this:
Quick Reference
| Method | What it does | Example result |
|---|---|---|
| `length()` | Number of characters | `"abc".length()` → 3 |
| `charAt(i)` | Character at index i | `"abc".charAt(1)` → `'b'` |
| `indexOf(s)` | First position of s, or -1 | `"abc".indexOf("c")` → 2 |
| `substring(a, b)` | Text from a up to b (b excluded) | `"abcd".substring(1,3)` → `"bc"` |
| `toUpperCase()` | All letters upper case | `"hi".toUpperCase()` → `"HI"` |
| `trim()` | Removes outer whitespace | `" x ".trim()` → `"x"` |
| `replace(a, b)` | Swaps a for b everywhere | `"aa".replace("a","b")` → `"bb"` |
| `equals(s)` | True if same characters | `"a".equals("a")` → true |
| `split(sep)` | Cuts string into an array | `"a,b".split(",")` → `["a","b"]` |
Key Ideas to Remember
- A
Stringis an object, so it has built-in methods. - Strings are immutable: methods return new strings, so save the result.
- Compare string contents with
.equals(), never==. - Indexes start at 0, and
substring's end index is excluded. - Use
+for simple joining andStringBuilderfor heavy building.
Exercise
What does this code print, and why? String s = "banana"; s.replace("a", "o"); System.out.println(s);
Show answer
It prints "banana". Strings are immutable, so replace() returns a new string ("bonono") and the original is untouched. The code fixes itself by writing s = s.replace("a", "o");, which then prints "bonono".
Exercise
Write an expression that gives the last character of any non-empty string word.
Show answer
word.charAt(word.length() - 1). Indexes start at 0, so the last position is the length minus one.