String Methods in Java
String has more than 60 methods, but a dozen of them do almost all the work in real programs: finding text, checking text, changing case, replacing and splitting. This lesson groups them by the job you're trying to do, so you know where to look. Remember one rule throughout: strings never change, so every method that "modifies" text returns a new string.
Finding Things in a String
Find.java▶ Try it
public class Find {
public static void main(String[] args) {
String t = "Navika Anamaneni, Hyderabad";
System.out.println(t.length());
System.out.println(t.charAt(7));
System.out.println(t.indexOf("a") + " " + t.lastIndexOf("a"));
System.out.println(t.indexOf('a', 2) + " " + t.indexOf("x"));
System.out.println(t.contains("Hyd") + " " + t.startsWith("Nav")
+ " " + t.endsWith("bad"));
}
}Output
27
A
1 25
5 -1
true true trueHow it works
length()counts every character, including spaces and the comma: 27.charAt(7)reads one character; position 7 is theAof "Anamaneni".indexOfreturns the first position of the text,lastIndexOfthe last. Both count from 0.indexOf('a', 2)starts looking at position 2. When nothing is found, the answer is -1.contains,startsWithandendsWithgive a simpletrueorfalse.
Changing Text into a New String
Change.java▶ Try it
import java.util.Arrays;
public class Change {
public static void main(String[] args) {
String raw = " Navika Anamaneni, Hyderabad ";
String t = raw.trim();
System.out.println("[" + t + "]");
System.out.println(t.toUpperCase());
System.out.println(t.replace('a', '@'));
System.out.println(t.replace("Hyderabad", "Pune"));
System.out.println(Arrays.toString(t.split(", ")));
System.out.println(Arrays.toString("abc".toCharArray()));
}
}Output
[Navika Anamaneni, Hyderabad]
NAVIKA ANAMANENI, HYDERABAD
N@vik@ An@m@neni, Hyder@b@d
Navika Anamaneni, Pune
[Navika Anamaneni, Hyderabad]
[a, b, c]How it works
trim()removes spaces at both ends. The brackets show exactly where the text starts and stops.toUpperCase()andtoLowerCase()change case.replaceswaps every match, whether a single character or a piece of text.split(", ")breaks the text into an array wherever", "appears.toCharArray()gives a copy of the characters as achar[].
Quick Reference by Job
| Job | Methods |
|---|---|
| Size and single characters | length(), charAt(i), isEmpty(), isBlank() |
| Searching | indexOf, lastIndexOf, contains, startsWith, endsWith |
| Comparing | equals, equalsIgnoreCase, compareTo (see "String Comparison in Java") |
| Cutting | substring (see "Substring in Java"), split |
| Changing case | toUpperCase(), toLowerCase() |
| Replacing | replace (plain text), replaceAll and replaceFirst (patterns) |
| Removing spaces | trim(), strip(), stripLeading(), stripTrailing() |
| Converting | toCharArray(), chars(), String.valueOf(x), getBytes() |
| Joining and repeating | String.join, repeat, concat |
Common Mistakes
Ignoring the return value. s.replace("a", "b"); alone changes nothing.
Splitting on ., | or + without escaping. They're special in patterns; use "\\.", "\\|" or "\\+".
Forgetting that indexOf returns -1. Check before using the position.
Practice
- Easy: For the sentence
"Java is fun and Java is fast", print the first and last positions of"Java", and the sentence with"Java"replaced by"Kotlin". - Harder: Given
"Navika:91,Srihitha:88,Advitha:95", split it into name-score pairs and print each on its own line asNavika scored 91.
Key Takeaways
Was this tutorial helpful?
Lesson 194 of 482