Core Java String and StringBuilder API Fundamentals

Understanding Java APIs

An API (Application Programming Interface) is a set of pre-built tools—classes, methods, and interfaces—that allow developers to interact with underlying functionality without needing to understand or reimplement low-level logic. In Java, the standard API is bundled in the JDK and includes well-documented classes such as Scanner, String, and StringBuilder.

To effectively use these APIs:

  • Consult the official Java SE Documentation
  • Navigate to the Index tab and search for a class name (e.g., Random)
  • Identify its package (e.g., java.util)
  • Read the class description, constructors, and method signatures

Reading Input with Scanner

The Scanner class provides flexible input parsing from streams like System.in. Key distinctions between its string-reading methods:

  • next(): reads up to the next delimiter (space, tab, or newline); stops at whitespace.
  • nextLine(): consumes the entire line, including spaces, until the newline character.

When mixing numeric and string inputs, avoid pairing nextInt() with nextLine() directly—nextInt() leaves the trailing newline in the buffer, causing nextLine() to return an empty string. Prefer next() for string input after numeric reads, or call nextLine() once to consume the leftover newline.

Example: Robust Input Handling

import java.util.Scanner;

public class InputHandler {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter age: ");
        int age = input.nextInt();
        input.nextLine(); // consume leftover newline

        System.out.print("Enter full name: ");
        String fullName = input.nextLine();

        System.out.printf("Age: %d, Name: '%s'%n", age, fullName);
    }
}

Immutability and Construction of Strings

The String class resides in java.lang and requires no explicit import. All string literals (e.g., "hello") are instances of String, and once created, their content cannot be altered—this immutability ensures thread safety and enables optimizations like string pooling.

Strings can be instantiated in two primary ways:

  • Direct assignment: String s = "test"; — references the string pool; identical literals share the same object.
  • Constructor invocation: String s = new String("test"); — always allocates a new object on the heap, even if content matches an existing pool entry.

Example: Constructor Variants

public class StringConstruction {
    public static void main(String[] args) {
        String empty = new String();                        // ""
        char[] letters = {'J', 'a', 'v', 'a'};
        String fromChars = new String(letters);             // "Java"
        String copy = new String("clone");                  // "clone"

        System.out.println(empty.isEmpty());                // true
        System.out.println(fromChars);                      // Java
        System.out.println(copy);                           // clone
    }
}

Comparing and Manipulating Strings

Use equals() (not ==) to compare string content. The == operator compares object references—not values—so it's unreliable for semantic equaliyt.

  • str1.equals(str2): case-sensitive comparison
  • str1.equalsIgnoreCase(str2): ignores case
  • str1.length(): returns number of UTF-16 code units
  • str1.charAt(i): retrieves character at index i
  • str1.toCharArray(): returns a mutable copy of characters
  • str1.substring(start, end): extracts substring [start, end)
  • str1.replace(old, new): returns new string with all occurrences replaced
  • str1.split(regex): splits on pattern and returns string array

Example: Practical String Operations

public class StringOperations {
    public static void main(String[] args) {
        String phone = "13812345678";
        String masked = phone.substring(0, 3) + "****" + phone.substring(7);
        System.out.println(masked); // 138****5678

        String raw = "This TMD message needs filtering.";
        String clean = raw.replace("TMD", "***");
        System.out.println(clean); // This *** message needs filtering.

        String studentData = "Alice,22";
        String[] parts = studentData.split(",");
        System.out.printf("Name: %s, Age: %s%n", parts[0].trim(), parts[1].trim());
    }
}

Mutable Strings with StringBuilder

Unlike String, StringBuilder is mutable and optimized for frequent modifications—ideal for concatenation, insertion, or reversal within loops. It avoids the memory overhead of creating intermediate objects.

Key operations include:

  • append(...): adds data and supports method chaining
  • reverse(): inverts character order in-place
  • toString(): converts back to immutable String

Example: Efficient Array Formatting

public class ArrayFormatter {
    public static String formatArray(int[] values) {
        if (values == null || values.length == 0) return "[]";

        StringBuilder builder = new StringBuilder("[");
        for (int i = 0; i < values.length; i++) {
            builder.append(values[i]);
            if (i < values.length - 1) builder.append(", ");
        }
        builder.append("]");
        return builder.toString();
    }

    public static void main(String[] args) {
        int[] nums = {42, -7, 0, 99};
        System.out.println(formatArray(nums)); // [42, -7, 0, 99]
    }
}

Tags: java string StringBuilder Scanner API

Posted on Sun, 04 Oct 2026 16:48:31 +0000 by nwp