Register

Java for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

String methods you will use daily

Objects and text11 min readLesson 3 of 5

3.1 Reading characters and pieces

A String holds a sequence of characters and provides methods for reading parts of it. Indexes start at 0, so the first character sits at position 0 and the last at length() - 1. charAt(index) returns one character, length() returns the number of characters, and substring(start, end) returns a new string from start up to but not including end.

indexOf(text) reports where a piece begins, or -1 when it does not appear. These methods do not change the original string; each one returns a result. Keeping that in mind prevents the common mistake of calling a method and ignoring its return value.

java
public class Main {
    public static void main(String[] args) {
        String course = "Java Notes";
        System.out.println(course.length());
        System.out.println(course.charAt(5));
        System.out.println(course.indexOf("Notes"));
        System.out.println(course.substring(5));
        System.out.println(course.substring(0, 4));
    }
}

Output

10
N
5
Notes
Java

3.1.1 Searching and checking

contains, startsWith, and endsWith answer yes or no questions about a string. isEmpty() is true only for a string of length 0. isBlank() is true when the string is empty or holds only whitespace, which makes it a better check after reading a line from a form.

indexOf returns -1 for a missing piece, so a search should compare the result with -1. A result of 0 means the match starts at the beginning. You can pass a second argument to indexOf to start the search at a given index when the same word appears more than once.

These checks return booleans, so they fit directly into an if condition. Use equals for a full-string comparison, which the comparison lesson covers, and these methods for partial checks.

java
public class Main {
    public static void main(String[] args) {
        String path = "notes/java/strings.md";
        System.out.println(path.contains("java"));
        System.out.println(path.startsWith("notes/"));
        System.out.println(path.endsWith(".md"));
        System.out.println(path.indexOf("python"));
        System.out.println("   ".isBlank());
        System.out.println("".isEmpty());
    }
}

Output

true
true
true
-1
true
true

3.1.2 Cleaning and replacing

strip() removes leading and trailing whitespace. trim() does a similar job for characters at or below U+0020, while strip() follows Unicode whitespace, so prefer it for modern text. Neither method changes the original; assign the result to keep the cleaned version.

replace(old, new) swaps every literal match. replaceAll takes a regular expression, and that is the one to reach for when the pattern is more than plain text. toUpperCase() and toLowerCase() change case without touching the original. repeat(count) returns the text repeated a number of times, which is useful for simple separators.

Chain calls only while the result stays easy to read. Three or four small transformations are fine. A longer chain is easier to debug when it is split across named variables.

java
public class Main {
    public static void main(String[] args) {
        String raw = "  Java Basics  ";
        String clean = raw.strip();
        System.out.println(clean.toUpperCase());
        System.out.println(clean.replace("Basics", "Collections"));
        System.out.println(clean.repeat(2));
        System.out.println(clean.length());
        System.out.println(raw.length());
    }
}

Output

JAVA BASICS
Java Collections
Java BasicsJava Basics
11
15

3.1.3 Splitting and joining

split(separator) cuts a string into an array of pieces. The separator is a regular expression, so a plain comma or semicolon works as expected. A trailing empty piece may be dropped. The two-argument form split(separator, limit) stops after a set number of pieces.

String.join(delimiter, pieces) goes the other way and places a delimiter between elements. It accepts an array or an Iterable, which makes it useful after filtering a list. Arrays.toString(array) shows the contents with brackets and commas when you need to inspect a split result.

Splitting a line of comma-separated values is a common first step in a small parser. Check the length before reading fixed positions, and strip each piece when the source may contain spaces around the delimiter.

java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String line = "red,green,blue";
        String[] parts = line.split(",");
        System.out.println(parts.length);
        System.out.println(Arrays.toString(parts));
        System.out.println(String.join(" | ", parts));
        System.out.println(line.split(",", 2).length);
    }
}

Output

3
[red, green, blue]
red | green | blue
2

3.1.4 A short pipeline

Most text work follows a pattern: clean the input, change the parts that need changing, then use the result. Method chaining expresses that pipeline in one expression. Each call returns a new string, so the chain reads from left to right.

For a slug, strip() removes the padding, toLowerCase() makes the text consistent, and replace(" ", "-") swaps spaces. The original variable still holds the padded text, which is useful when both versions are needed.

When a chain grows, store intermediate values with names. A reader can then see which step produced which text, and a test can check one step at a time.

java
public class Main {
    public static void main(String[] args) {
        String title = "  java collections guide  ";
        String slug = title.strip().toLowerCase().replace(" ", "-");
        System.out.println(slug);
        System.out.println(slug.startsWith("java-"));
        System.out.println(title.length());
        System.out.println(title.strip().length());
    }
}

Output

java-collections-guide
true
26
22

3.1.5 Practice

  1. Take " Report: March " and print its stripped length and uppercase form.
  2. Split "north,east,south,west" and print each direction on its own line.
  3. Join the same pieces with " > " and print the result.
  4. Find the second occurrence of "a" in "banana" with indexOf and a start index.
  5. Build a slug from a title with mixed case and extra spaces.

For step 5, print both the original title and the slug, then check that the original still has its spaces.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What does `substring(2, 5)` return?

    It returns the characters at indexes 2, 3, and 4. The start index is included and the end index is excluded.

  • 02Why does `indexOf` return -1?

    It reports that the requested text does not occur in the string. A valid position is 0 or greater.

  • 03Do string methods modify the original string?

    No. A `String` is immutable, so methods such as `strip` and `replace` return a new string. Assign the result to keep it.