Java course menu
Java Strings: Methods, Comparison with equals, Immutability and Formatting
Learn Java strings: creating strings, length and charAt, substring, indexOf and contains, replace, split and join, trim and strip, case conversion, comparing with equals vs ==, immutability and the string pool, String.format, and text blocks.
On this page
Text is everywhere in programs: names, messages, file contents, commands. In Java, text is represented by the String class, which comes with dozens of useful methods. Strings are immutable: no method ever changes a string; methods that "modify" text return a new string.
Creating and joining strings#
public class Main {
public static void main(String[] args) {
String first = "Asha";
String last = "Rao";
String full = first + " " + last;
full += "!";
System.out.println(full);
System.out.println("Length: " + full.length());
System.out.println("-".repeat(10));
}
}Asha Rao!
Length: 9
----------Characters and positions#
Each character has an index starting at 0. charAt(i) returns one char:
public class Main {
public static void main(String[] args) {
String word = "Java";
System.out.println(word.charAt(0) + " " + word.charAt(word.length() - 1));
for (char c : word.toCharArray()) {
System.out.print(c + "-");
}
System.out.println();
}
}J a
J-a-v-a-Searching and substrings#
public class Main {
public static void main(String[] args) {
String email = "asha.rao@example.com";
int at = email.indexOf('@');
String user = email.substring(0, at); // from 0 up to (not including) at
String domain = email.substring(at + 1); // from at + 1 to the end
System.out.println(user + " | " + domain);
System.out.println(email.contains("example") + " " + email.endsWith(".com"));
System.out.println(email.indexOf("xyz"));
System.out.println(email.lastIndexOf('a'));
}
}asha.rao | example.com
true true
-1
11substring(start, end)includesstartand excludesend.indexOfreturns-1when the text is not found.startsWith,endsWithandcontainsanswer yes/no questions.
Changing text (returns a new string)#
public class Main {
public static void main(String[] args) {
String s = " I like tea ";
System.out.println("[" + s.trim() + "]");
System.out.println(s.strip().replace("tea", "coffee"));
System.out.println(s.toUpperCase().strip());
System.out.println("[" + s + "]"); // unchanged: strings are immutable
}
}[I like tea]
I like coffee
I LIKE TEA
[ I like tea ]strip() (Java 11) removes all kinds of whitespace, including Unicode spaces; trim() removes only basic ASCII whitespace.
Splitting and joining#
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
String csv = "Asha,Pune,21";
String[] parts = csv.split(",");
System.out.println(parts[1] + " (" + parts.length + " fields)");
String sentence = "practice makes progress";
String[] words = sentence.split("\\s+"); // one or more spaces
System.out.println(Arrays.toString(words));
System.out.println(String.join(" | ", List.of("a", "b", "c")));
}
}Pune (3 fields)
[practice, makes, progress]
a | b | csplit takes a regular expression: "\\s+" means "one or more whitespace characters". Characters with special meaning in regex, such as . and |, must be escaped: split("\\.").
Comparing strings: equals, never ==#
== checks whether two variables refer to the same object. Use equals to compare the text:
public class Main {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b); // true: same pooled literal
System.out.println(a == c); // false: different objects
System.out.println(a.equals(c)); // true: same text
System.out.println("Hello".equalsIgnoreCase(a));
System.out.println("apple".compareTo("banana") < 0);
}
}true
false
true
true
trueIdentical string literals share one object in the string pool, which is why a == b happens to be true. Strings created at run time (from input, files or new String) are different objects, so == gives unreliable results. Always use equals. compareTo orders strings alphabetically (negative, zero or positive).
Immutability#
Because strings never change, they can be shared safely and used as keys in maps. The cost: building a string piece by piece with += in a loop creates a new string every time. For that, use StringBuilder.
Formatting#
String.format (and its shortcut "...".formatted(...)) builds strings from placeholders, like printf:
public class Main {
public static void main(String[] args) {
String name = "Asha";
double balance = 2500.756;
System.out.println(String.format("%s has Rs %.2f", name, balance));
System.out.println("|%-8s|%8s|".formatted("left", "right"));
System.out.println("%05d".formatted(42));
}
}Asha has Rs 2500.76
|left | right|
00042Text blocks#
Java 15 added text blocks for multi-line strings, written between triple quotes. Indentation common to all lines is removed automatically:
public class Main {
public static void main(String[] args) {
String json = """
{
"name": "Asha",
"city": "Pune"
}
""";
System.out.print(json);
}
}{
"name": "Asha",
"city": "Pune"
}Common mistakes#
Practice#
Practice exercise
Write boolean isPalindrome(String s) that ignores spaces and case, and test it with "Never odd or even" and "Java".
Show solution
public class Palindrome {
static boolean isPalindrome(String s) {
String cleaned = s.replace(" ", "").toLowerCase();
String reversed = new StringBuilder(cleaned).reverse().toString();
return cleaned.equals(reversed);
}
public static void main(String[] args) {
System.out.println(isPalindrome("Never odd or even"));
System.out.println(isPalindrome("Java"));
}
}true
falsePractice exercise
Capitalize the first letter of every word in "the quick brown fox".
Show solution
public class TitleCase {
public static void main(String[] args) {
String sentence = "the quick brown fox";
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
String w = words[i];
words[i] = Character.toUpperCase(w.charAt(0)) + w.substring(1);
}
System.out.println(String.join(" ", words));
}
}The Quick Brown FoxKey takeaway#
Finished this lesson?