Java + Spring Boot track

Lesson 17 · Part 4: Exceptions & I/O

String Handling

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…

Part 4: Exceptions & I/O3 min readFree lesson

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 String being 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

  1. Use == to compare String → .equals() or .equalsIgnoreCase()
  2. Combining + in a loop (performance) → StringBuilder
  3. Misunderstanding that end of substring(begin, end) is inclusive
  4. Write a regular expression with a single backslash (Java string requires \\)
  5. Use only \n instead of %n for format (most works, but OS compatible is %n)

Cleanup

  • String is immutable, repeated combination is StringBuilder
  • Take care of readability with String.format and 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

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/FormatAndTextBlock.javaJava
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);
    }
}
src/Immutability.javaJava
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");
    }
}
src/RegexDemo.javaJava
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());
    }
}
src/StringMethods.javaJava
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);
        }
    }
}

Assignment

Problem 1 — Palindrome identification

  • File name: Homework01.java
  • Core concept: String basic method

Requirements

  • static boolean isPalindrome(String s) — Ignore spaces, ignore case.
  • Test input: "level", "Hello", "A man a plan a canal Panama"

Expected output

level -> true
Hello -> false
A man a plan a canal Panama -> true

Problem 2 — Email extraction

  • File name: Homework02.java
  • Key concept: regular expressions

Requirements

Expected output

[email protected]
[email protected]

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

Homework01.javaJava
/** Palindrome identification.*/
public class Homework01 {
    public static void main(String[] args) {
        String[] cases = { "level", "Hello", "A man a plan a canal Panama" };
        for (String s : cases) {
            System.out.println(s + " -> " + isPalindrome(s));
        }
    }

    static boolean isPalindrome(String s) {
        String t = s.replace(" ", "").toLowerCase();
        return t.equals(new StringBuilder(t).reverse().toString());
    }
}
Homework02.javaJava
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Email extraction.*/
public class Homework02 {
    public static void main(String[] args) {
        String text = "Inquiry: [email protected] or [email protected]";
        Pattern p = Pattern.compile("[\\w.]+@[\\w.]+");
        Matcher m = p.matcher(text);
        while (m.find()) {
            System.out.println(m.group());
        }
    }
}

Learn this lesson with a mentor

Work through the Java + Spring Boot track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now