Java · Lesson 7 of 15
Strings and StringBuilder
Immutable strings, common methods, comparison and building text efficiently.
- Beginner
- 12 min read
- 3 objectives
Before this lessonLesson 6: Exception Handling
What you will learn
- Use core String methods
- Compare with equals
- Build text with StringBuilder
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
A String is a sequence of characters. In Java strings are immutable: every operation that seems to change one actually returns a new string, and the original stays untouched.
Everyday methods
public class Main {
public static void main(String[] args) {
String s = " Hello, Java ";
System.out.println(s.trim());
System.out.println(s.toUpperCase());
System.out.println(s.length());
System.out.println(s.trim().substring(0, 5));
System.out.println(s.contains("Java"));
System.out.println(s.replace("Java", "World").trim());
}
}Output
Hello, Java HELLO, JAVA 15 Hello true Hello, World
Comparing strings
Never compare strings with ==. It checks whether two variables point at the same object, not whether the text matches. Use equals.
public class Main {
public static void main(String[] args) {
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println("Hi".equalsIgnoreCase("hI"));
}
}Output
false true true
Splitting, joining and formatting
public class Main {
public static void main(String[] args) {
String[] parts = "a,b,c".split(",");
System.out.println(parts.length);
System.out.println(String.join("-", parts));
System.out.println(String.format("%s scored %d (%.1f%%)", "Ada", 42, 93.456));
}
}Output
3 a-b-c Ada scored 42 (93.5%)
StringBuilder
Because strings are immutable, gluing many pieces in a loop with + creates many throwaway objects. StringBuilder is a mutable buffer built for this.
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append(i).append(' ');
}
System.out.println(sb.toString().trim());
System.out.println(sb.reverse().toString().trim());
}
}Output
ArraysFixed-size arrays, loops over them, 2D arrays and the Arrays utility class.
1 2 3 4 5 5 4 3 2 1
