Java for Beginners · Module 5: Data and Methods
🎯 Working With Text
Lesson 23 showed what a String is. This lesson shows what you can do with one: search it, cut it, change its case, split it into words. Because Strings never change, every one of these methods gives back a new value. When you need to build or edit text repeatedly, StringBuilder is the better tool.
1️⃣ The Everyday String Methods
| Method | What it does | Example | Result |
length() | number of characters | "Java".length() | 4 |
charAt(i) | character at index i | "Java".charAt(2) | v |
indexOf(x) | first position, or -1 | "Java".indexOf('a') | 1 |
substring(a, b) | part from a up to b | "Java".substring(1, 3) | av |
toUpperCase() | capital letters | "Java".toUpperCase() | JAVA |
trim() | removes spaces at both ends | " hi ".trim() | hi |
replace(a, b) | swaps text | "Java".replace('a', 'o') | Jovo |
contains(x) | true if x occurs inside | "Java".contains("av") | true |
split(sep) | cuts into an array | "a,b".split(",") | [“a”, “b”] |
Figure 2: The String methods you will use most.
0a
1v
2a
3␣
4P
5r
6o
7g
8r
9a
10m
11m
12i
13n
14g
15
substring(5) = “Programming” (from index 5 to the end). substring(0, 4) = “Java” (index 0 up to, but not including, index 4).Figure 1: How substring uses indexes.
Program 1: A tour of the methods
public class StringMethods {
public static void main(String[] args) {
String s = " Java Programming ";
System.out.println("[" + s + "]");
System.out.println("trim : [" + s.trim() + "]");
String t = s.trim();
System.out.println("upper : " + t.toUpperCase());
System.out.println("lower : " + t.toLowerCase());
System.out.println("length : " + t.length());
System.out.println("charAt(5) : " + t.charAt(5));
System.out.println("indexOf(a) : " + t.indexOf('a'));
System.out.println("lastIndexOf : " + t.lastIndexOf('a'));
System.out.println("indexOf(xyz): " + t.indexOf("xyz"));
System.out.println("substring(5): " + t.substring(5));
System.out.println("substring(0,4): " + t.substring(0, 4));
System.out.println("contains : " + t.contains("gram"));
System.out.println("startsWith : " + t.startsWith("Java"));
System.out.println("endsWith : " + t.endsWith("ing"));
System.out.println("replace : " + t.replace('a', '@'));
System.out.println("isEmpty : " + "".isEmpty());
System.out.println("isBlank : " + " ".isBlank());
System.out.println("repeat : " + "ab".repeat(3));
}
}
[ Java Programming ]
trim : [Java Programming]
upper : JAVA PROGRAMMING
lower : java programming
length : 16
charAt(5) : P
indexOf(a) : 1
lastIndexOf : 10
indexOf(xyz): -1
substring(5): Programming
substring(0,4): Java
contains : true
startsWith : true
endsWith : true
replace : J@v@ Progr@mming
isEmpty : true
isBlank : true
repeat : ababab
- Square brackets in the output show where the spaces were removed by
trim(). indexOfreturns the first position of a character or text, and -1 if it is not found.lastIndexOfsearches from the end.substring(begin, end)includesbeginbut excludesend.substring(5)runs to the end.replacereplaces every occurrence, not just the first.isEmpty()is true only for length 0.isBlank()is also true for spaces only.- Every call here returned a new String. The variable
titself never changed.
2️⃣ Splitting, Joining and Converting
import java.util.Arrays;
public class SplitJoin {
public static void main(String[] args) {
String line = "Ajay,Rahul,Priya,Sana";
String[] names = line.split(",");
System.out.println("count = " + names.length);
System.out.println(Arrays.toString(names));
String sentence = "Learning Java is fun";
String[] words = sentence.split("\\s+");
System.out.println(Arrays.toString(words));
System.out.println(String.join("-", names));
char[] chars = "hello".toCharArray();
Arrays.sort(chars);
System.out.println(new String(chars));
System.out.println(String.valueOf(3.5) + String.valueOf(true));
System.out.println(String.format("%s scored %d (%.1f%%)", "Ajay", 87, 87.0));
}
}
count = 4
[Ajay, Rahul, Priya, Sana]
[Learning, Java, is, fun]
Ajay-Rahul-Priya-Sana
ehllo
3.5true
Ajay scored 87 (87.0%)
split(",")cuts a String at every comma and returns an array (Lesson 21)."\\s+"means “one or more spaces”. In Java source the backslash is doubled (Lesson 11). It handles the extra spaces in the sentence.String.joinglues an array back together with a separator.toCharArray()turns a String into achar[]. Sorting the characters of “hello” gives “ehllo”, which is a useful step in anagram checks.String.valueOf(...)turns any value into a String (Lesson 9).String.formatbuilds text from a pattern:%sfor text,%dfor an int,%.1ffor one decimal place, and%%for a percent sign.
3️⃣ Putting Methods Together
public class Utility {
public static void main(String[] args) {
String text = "Madam";
String rev = "";
for (int i = text.length() - 1; i >= 0; i--) {
rev += text.charAt(i);
}
System.out.println("reverse = " + rev);
System.out.println("palindrome = " + text.equalsIgnoreCase(rev));
String sentence = "Java is a popular language";
int vowels = 0;
for (char c : sentence.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) >= 0) vowels++;
}
System.out.println("vowels = " + vowels);
System.out.println("words = " + sentence.split(" ").length);
}
}
reverse = madaM
palindrome = true
vowels = 11
words = 5
- Reversing walks the String from the last index down to 0 and builds the answer one character at a time.
equalsIgnoreCasemakes the palindrome check ignore capitals: “Madam” and “madaM” match.- Vowel counting uses a neat trick:
"aeiou".indexOf(c)is 0 or more only whencis a vowel.
4️⃣ StringBuilder: Text You Can Edit
| String | StringBuilder | |
| Changeable? | No (immutable) | Yes (mutable) |
| Each change | creates a new object | edits the same object |
| Joining in a loop | slow | fast |
| Thread-safe? | Yes (cannot change) | No (use StringBuffer if needed) |
| Use for | fixed text, keys, comparisons | building or editing text |
Figure 3: String versus StringBuilder.
Joining Strings with += in a loop makes a new String each time. StringBuilder keeps one buffer and edits it in place.
public class SbDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" is").append(" fun");
System.out.println(sb);
sb.insert(0, ">> ");
System.out.println(sb);
sb.replace(3, 7, "JAVA");
System.out.println(sb);
sb.delete(0, 3);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
sb.setLength(4);
System.out.println(sb + " | length = " + sb.length());
String result = sb.toString();
System.out.println(result.toUpperCase());
}
}
Java is fun
>> Java is fun
>> JAVA is fun
JAVA is fun
nuf si AVAJ
nuf | length = 4
NUF
appendadds at the end and returns the same builder, so calls can be chained:sb.append(" is").append(" fun").insert(index, text),replace(start, end, text),delete(start, end)andreverse()all change the same object.setLength(4)cuts the content to 4 characters.- When you need a normal String (to compare it, for example), call
toString().
Program 5: Why it matters: speed
public class Speed {
public static void main(String[] args) {
int n = 50000;
long t1 = System.nanoTime();
String s = "";
for (int i = 0; i < n; i++) {
s += "x";
}
long stringMs = (System.nanoTime() - t1) / 1_000_000;
long t2 = System.nanoTime();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append("x");
}
long sbMs = (System.nanoTime() - t2) / 1_000_000;
System.out.println("lengths equal: " + (s.length() == sb.length()));
System.out.println("String += took ms : " + stringMs);
System.out.println("StringBuilder ms : " + sbMs);
}
}
lengths equal: true
String += took ms : 268
StringBuilder ms : 1
- Both loops build the same 50,000-character text. The
Stringloop created 50,000 temporary Strings and was hundreds of times slower here. - The exact numbers depend on the computer and change every run. The gap is what matters: use
StringBuilderwhen you build text in a loop. - Java also has
StringBuffer, the older, thread-safe twin of StringBuilder. Prefer StringBuilder in ordinary programs.
5️⃣ Errors Beginners Meet
String and StringBuilder are different types
public class Bad1 {
public static void main(String[] args) {
String s = "Java";
StringBuilder sb = "Java";
String t = new StringBuilder("x");
}
}
Bad1.java:4: error: incompatible types: String cannot be converted to StringBuilder
StringBuilder sb = “Java”;
^
Bad1.java:5: error: incompatible types: StringBuilder cannot be converted to String
String t = new StringBuilder(“x”);
^
2 errors
- Create a builder with
new StringBuilder("Java"), and convert back withtoString().
substring beyond the end
public class Sub {
public static void main(String[] args) {
String s = "Java";
System.out.println(s.substring(2, 9));
}
}
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: Range [2, 9) out of bounds for length 4
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
… (several internal lines)
at java.base/java.lang.String.substring(String.java:2823)
at Sub.main(Sub.java:4)
- The end index cannot be larger than
length(). The first line says exactly which range was wrong.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
s.trim(); without storing | Result is thrown away | s = s.trim(); |
Thinking substring(0, 4) includes index 4 | End index is excluded | Remember: begin included, end excluded |
Forgetting indexOf returns -1 | Using -1 as an index crashes | Check != -1 first |
Comparing sb == "text" | Different types | sb.toString().equals("text") |
Joining Strings in a big loop with += | Very slow | Use StringBuilder |
Single backslash in split("\s") | Invalid escape | Double it: "\\s" |
❓ Frequently Asked Questions
Q1. How do I change one character inside a String?
You cannot. Use replace, build a new String, or use a StringBuilder with setCharAt.
Q2. What is the difference between replace and replaceAll?replace works on plain text. replaceAll treats the first argument as a pattern (a regular expression).
Q3. How do I compare two StringBuilders?
Not with equals, which compares references. Compare sb1.toString().equals(sb2.toString()).
Q4. Is split(“,”) safe for special characters?
Characters like . and | have special meaning in patterns, so escape them: split("\\.").
✅ Key Takeaways
- String methods (
length,charAt,indexOf,substring,replace,trim,toUpperCase,split) return new values and never change the original. substring(begin, end)excludesend.indexOfreturns -1 when nothing is found.String.join,valueOf,formatandtoCharArrayconvert between Strings, arrays and values.StringBuilderis mutable:append,insert,delete,reverse. Use it to build text in loops.- Call
toString()to get a String from a builder.
🎓 Practice questions: (1) Count how many times a given letter appears in a String. (2) Check whether two Strings are anagrams (usetoCharArrayandArrays.sort). (3) Print the first letter of each word in a sentence. (4) Reverse a String usingStringBuilder. (5) Explain whys.toUpperCase();does nothing on its own.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java