String (String) is a data type that is indispensable in any program. Java's String is immutable, and in cases where changes are frequent, StringBuilder is used together. Regular expressions (Pattern/Matcher) are powerful tools for search and substitution.
Learning Objectives
- Know the main methods of
String(length,substring,indexOf,split,trim, etc.) - Know the cost when combined with the meaning of
Stringbeing immutable - Optimize repeat combination with
StringBuilder - Create a good-looking string with
String.format - View basic usage of regular expressions (
Pattern.compile,matcher.find)
Key concepts
1) Immutability
String a = "Hello";
String b = a.replace("e", "a");
System.out.println(a); //Hello (a does not change)
System.out.println(b); // Hallo
The String method returns a new string and does not replace the original.
2) Main method
"Java".length(); // 4
"Java".substring(1, 3); // av
"Hello, World".indexOf(","); // 5
" hi ".trim(); // "hi"
"a,b,c".split(","); // ["a","b","c"]
String.join("-", "a","b","c"); // "a-b-c"
3) StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i).append(",");
System.out.println(sb.toString()); // 0,1,2,3,4,
String concatenation within a loop is much faster with StringBuilder.
4) String.format / text block
String row = String.format("Name=%s, Score=%d", "exponent", 95);
String json = """
{
"name": "exponent",
"score": 95
}
""";
5) Regular expressions
import java.util.regex.Pattern;
import java.util.regex.Matcher;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("Order number: 1234, Price: 5678");
while (m.find()) {
System.out.println(m.group());
}
See as example
Example 1 — StringMethods.java: Main method
public class StringMethods {
public static void main(String[] args) {
String s = " Hello, Java World ";
System.out.println("length=" + s.length());
System.out.println("trim=" + s.trim() + "|");
System.out.println("upper=" + s.toUpperCase());
System.out.println("startsWith Hello? " + s.trim().startsWith("Hello"));
System.out.println("sub=" + s.trim().substring(7, 11));
System.out.println("rep=" + s.trim().replace("Java", "Spring"));
for (String w : s.trim().split(",\\s*")) {
System.out.println("token=" + w);
}
}
}
Execution result
length=19
trim=Hello, Java World|
upper= HELLO, JAVA WORLD
startsWith Hello? true
sub=Java
rep=Hello, Spring World
token=Hello
token=Java World
Note: end of substring(begin, end) is exclusive.
Example 2 — Immutability.java: Immutability and Cost
public class Immutability {
public static void main(String[] args) {
String s = "X";
long start = System.nanoTime();
for (int i = 0; i < 1000; i++) s += "Y";
long t1 = System.nanoTime() - start;
System.out.println("String += length=" + s.length() + ", time =" + t1 + "ns");
StringBuilder sb = new StringBuilder("X");
long start2 = System.nanoTime();
for (int i = 0; i < 1000; i++) sb.append("Y");
long t2 = System.nanoTime() - start2;
System.out.println("StringBuilder length=" + sb.length() + ", time =" + t2 + "ns");
}
}
Run results (time values vary from run to run)
String += length=1001, time=...ns
StringBuilder length=1001, time=...ns
Note: Iterative joins are almost always much faster with StringBuilder.
Example 3 — FormatAndTextBlock.java: Formatting
public class FormatAndTextBlock {
public static void main(String[] args) {
String row = String.format("Name=%s, Score=%d, Average=%.2f", "exponent", 95, 82.345);
System.out.println(row);
String json = """
{
"name": "exponent",
"score": 95
}
""";
System.out.println(json);
}
}
Execution result
Name=Index, Score=95, Average=82.35
{
"name": "exponent",
"score": 95
}
Memo: The indentation of a text block is based on the space length of the shortest line.
Example 4 — RegexDemo.java: Regular expression
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
String text = "Order number: 1234, Price: KRW 5678, Quantity: 3";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println("match=" + m.group());
}
Pattern email = Pattern.compile("[\\w.]+@[\\w.]+");
System.out.println(email.matcher("hi [email protected] bye").find());
}
}
Execution result
match=1234
match=5678
match=3
true
Note: \d in a Java string must be backslashed twice as \\d.
Common Mistakes
- Use
==to compareString→.equals()or.equalsIgnoreCase() - Combining
+in a loop (performance) →StringBuilder - Misunderstanding that
endofsubstring(begin, end)is inclusive - Write a regular expression with a single backslash (Java string requires
\\) - Use only
\ninstead of%nforformat(most works, but OS compatible is%n)
Cleanup
Stringis immutable, repeated combination isStringBuilder- Take care of readability with
String.formatand text block - Regular expressions are powerful, but difficult to read and debug — only when needed
- Empty string/null check is always conscious
Try it yourself
cd 04_Exception_Input/Output/17_String_Processing/src
javac StringMethods.java
java StringMethods