2.4 String Methods, StringBuilder Operations, and Type Parsing

Key Takeaways

  • Core String methods — length(), charAt(), substring(), indexOf(), lastIndexOf(), trim(), replace(), toLowerCase(), and toUpperCase() — all use 0-based indexing, and substring(beginIndex, endIndex) returns beginIndex inclusive through endIndex exclusive (length endIndex - beginIndex), throwing StringIndexOutOfBoundsException on invalid bounds.
  • String concatenation via the + operator evaluates strictly left-to-right following operator precedence, converting non-string operands to strings once a String operand is encountered.
  • StringBuilder provides a mutable alternative to String for efficient string manipulation, modifying its internal character buffer in place through append(), insert(), delete(), and reverse() without generating intermediate discarded objects.
  • Primitives are parsed from strings using wrapper class methods such as Integer.parseInt() and Double.parseDouble() which throw NumberFormatException on invalid inputs, while Boolean.parseBoolean() evaluates safely without throwing exceptions.
  • System.out.printf writes formatted text straight to the console and returns the PrintStream, while String.format prints nothing and returns a new String; %d accepts integral values, %s accepts any value including null, %f defaults to six decimal places, %n emits the platform line separator and consumes no argument, and a mismatched specifier such as %d with a double throws IllegalFormatConversionException at runtime rather than failing to compile.
Last updated: September 2026

2.4 String Methods, StringBuilder Operations, and Type Parsing

Quick Summary: Fluent string manipulation requires mastering core String methods, string concatenation evaluation precedence, mutable StringBuilder operations, and parsing utilities. String methods operate with 0-based indexing and always return new instances. For heavy repetitive modifications, StringBuilder avoids memory churn by altering an internal character buffer in place. Converting text to primitives utilizes wrapper methods like Integer.parseInt() and Double.parseDouble(), which require strict format validation to avoid runtime exceptions.


1. String Concatenation Mechanics & Precedence

The plus operator (+) is overloaded in Java. When applied to two numeric primitives, it performs mathematical addition. However, if either operand is a String, it acts as the string concatenation operator, converting the other operand to its text representation and combining them.

Left-to-Right Evaluation Rules

Java evaluates expressions strictly from left to right, respecting standard mathematical operator precedence (*, /, % execute before +, -):

System.out.println(10 + 20 + "Java");   // Prints "30Java"
// Step 1: 10 + 20 -> 30 (integer addition)
// Step 2: 30 + "Java" -> "30Java" (string concatenation)

System.out.println("Java" + 10 + 20);   // Prints "Java1020"
// Step 1: "Java" + 10 -> "Java10" (string concatenation)
// Step 2: "Java10" + 20 -> "Java1020" (string concatenation)

System.out.println("Java" + (10 + 20)); // Prints "Java30"
// Parentheses force addition first: 10 + 20 -> 30, then "Java" + 30 -> "Java30"

System.out.println(10 + 20 + "Java" + 30 + 40); // Prints "30Java3040"

+ Operator vs. concat() Method

While the + operator gracefully converts null to the four-character string "null", the String.concat(String str) method strictly requires an object argument. Passing null to concat() causes an immediate NullPointerException:

String s = "Data";
System.out.println(s + null);       // Compiles and prints "Datanull"
// System.out.println(s.concat(null)); // RUNTIME ERROR: java.lang.NullPointerException

2. Essential java.lang.String Methods

The 1Z0-811 examination expects comprehensive knowledge of the core methods provided by java.lang.String.

String Inspection Methods

  • int length(): Returns the total count of UTF-16 characters in the string. (Contrast with arrays which use the .length field without parentheses!).
  • char charAt(int index): Returns the character at the specified 0-based index. If the index is negative or >= length(), the JVM throws StringIndexOutOfBoundsException.
  • int indexOf(String str) / int indexOf(char ch): Returns the 0-based index of the first occurrence of the target character or substring. Returns -1 if not found.
  • int indexOf(String str, int fromIndex): Searches forward starting at fromIndex.
  • int lastIndexOf(String str): Returns the index of the last occurrence of the target, searching backward from the end of the string.
  • boolean startsWith(String prefix) / boolean endsWith(String suffix): Tests whether the string begins or ends with the specified text.
  • boolean contains(CharSequence s): Returns true if the sequence appears anywhere within the string.
  • boolean isEmpty(): Returns true if and only if length() == 0.

String Manipulation Methods (Always Return New Strings!)

  • String substring(int beginIndex): Returns a new string extracting characters starting from beginIndex through the end of the string.
  • String substring(int beginIndex, int endIndex):
    • CRITICAL EXAM RULE: The substring begins at beginIndex (inclusive) and extends up to endIndex (exclusive).
    • The length of the resulting substring is always endIndex - beginIndex.
    • If beginIndex == endIndex, it returns an empty string "".
    • If beginIndex < 0, endIndex > length(), or beginIndex > endIndex, it throws StringIndexOutOfBoundsException.
String text = "Foundations";
// Index:      01234567890

System.out.println(text.substring(0, 5)); // "Found" (indexes 0, 1, 2, 3, 4; length = 5 - 0 = 5)
System.out.println(text.substring(5));    // "ations" (indexes 5 through 10)
  • String toLowerCase() / String toUpperCase(): Returns a new string with all characters converted to lowercase or uppercase according to the default locale.
  • String trim(): Returns a new string with all leading and trailing whitespace (spaces, tabs \t, newlines \n) removed. Internal whitespace between words is completely preserved.
  • String replace(char oldChar, char newChar): Returns a new string where every occurrence of oldChar is replaced with newChar.
  • String replace(CharSequence target, CharSequence replacement): Replaces all occurrences of the target sequence with the replacement sequence.

Method Chaining on String

Because every manipulation method returns a String reference, multiple method calls can be chained together in a single statement. Execution proceeds strictly from left to right:

String rawInput = "   Java Certified Associate   ";
String clean = rawInput.trim().toUpperCase().substring(0, 4);
System.out.println(clean); // Prints "JAVA"

3. The StringBuilder Class: Mutable Character Sequences

Because String is immutable, performing frequent string modifications (such as in a loop) creates numerous short-lived intermediate String objects, causing memory fragmentation and garbage collection overhead.

To solve this, Java provides java.lang.StringBuilder. A StringBuilder object represents a mutable sequence of characters. Modifications alter the internal character buffer in place without creating new objects.

String Concatenation in Loop (Inefficient):     StringBuilder in Loop (Efficient):
Allocates N discarded intermediate objects     Modifies single internal buffer in place

"a"                                            +-------------------------------+
"a" + "b" -> "ab" (garbage)                    | StringBuilder Buffer          |
"ab" + "c" -> "abc" (garbage)                  | ['a', 'b', 'c', 'd', ...]     |
"abc" + "d" -> "abcd"                          +-------------------------------+

Core StringBuilder Methods

  • StringBuilder append(...): Appends the string representation of any primitive, character array, or object to the end of the buffer. Returns a reference to this (the same StringBuilder instance).
  • StringBuilder insert(int offset, ...): Inserts data at the specified index, shifting existing characters to the right. Returns this.
  • StringBuilder delete(int start, int end): Removes characters from start (inclusive) up to end (exclusive). Returns this.
  • StringBuilder deleteCharAt(int index): Removes the character at the specified index. Returns this.
  • StringBuilder reverse(): Reverses the character sequence in place. Returns this.
  • String toString(): Constructs and returns a standard immutable String containing the buffer contents.
  • int length(): Returns the count of characters currently stored in the buffer.
  • int capacity(): Returns the total number of characters the current internal buffer can hold without reallocating.

Code Demonstration: StringBuilder Mutation

StringBuilder sb = new StringBuilder("Java");
sb.append(" 8");                 // Buffer is now "Java 8"
sb.insert(4, " SE");             // Buffer is now "Java SE 8"
sb.delete(4, 7);                 // Deletes ' ', 'S', 'E' -> Buffer is now "Java 8"
sb.reverse();                    // Buffer is now "8 avaJ"

System.out.println(sb.toString()); // Prints "8 avaJ"

The StringBuilder.equals() Exam Trap

CRITICAL EXAM RULE: Unlike the String class, StringBuilder does NOT override the equals() method from java.lang.Object. Therefore, invoking sb1.equals(sb2) evaluates reference equality (==), NOT content equality!

StringBuilder sb1 = new StringBuilder("Test");
StringBuilder sb2 = new StringBuilder("Test");

System.out.println(sb1 == sb2);      // false: different heap objects
System.out.println(sb1.equals(sb2)); // false! StringBuilder does NOT override equals()!

// To compare contents, convert both to String first:
System.out.println(sb1.toString().equals(sb2.toString())); // true: compares text content

4. Parsing Strings to Primitives and Vice Versa

A common requirement on Exam 1Z0-811 is converting textual strings into numeric primitives and converting primitives into strings.

Parsing Strings into Primitives (Wrapper Methods)

Each numeric wrapper class provides a static parse... method that reads text and returns a primitive value:

  • Integer.parseInt(String s): Parses a string into a primitive int.
  • Double.parseDouble(String s): Parses a string into a primitive double.
  • Long.parseLong(String s): Parses a string into a primitive long.
  • Boolean.parseBoolean(String s): Parses a string into a primitive boolean.
int count = Integer.parseInt("150");          // Returns primitive int 150
double taxRate = Double.parseDouble("0.0825"); // Returns primitive double 0.0825
long population = Long.parseLong("8000000000"); // Returns primitive long 8000000000L

Handling NumberFormatException (Exam Trap)

If the string passed to Integer.parseInt() or Double.parseDouble() contains non-digit characters, leading/trailing whitespace, extra decimal points, or is empty, the method throws a runtime java.lang.NumberFormatException:

// int err1 = Integer.parseInt(" 123 "); // THROWS NumberFormatException (spaces not trimmed!)
// int err2 = Integer.parseInt("12.5");  // THROWS NumberFormatException (decimal in int)
// int err3 = Integer.parseInt("$50");   // THROWS NumberFormatException (currency symbol)

The Special Behavior of Boolean.parseBoolean()

Unlike numeric parsing methods, Boolean.parseBoolean(String s) never throws an exception under any circumstances:

  • Returns true if and only if the argument is non-null and equals "true" ignoring case ("true", "True", "TRUE").
  • Returns false for any other input, including "false", "yes", "1", random gibberish, empty strings, and null.
System.out.println(Boolean.parseBoolean("true"));  // true
System.out.println(Boolean.parseBoolean("TRUE"));  // true
System.out.println(Boolean.parseBoolean("false")); // false
System.out.println(Boolean.parseBoolean("yes"));   // false (no exception!)
System.out.println(Boolean.parseBoolean(null));    // false (no exception!)

Converting Primitives to Strings

To convert any primitive value into a String, use one of three techniques:

  1. String.valueOf(...) (Recommended & Best Practice):
    String s1 = String.valueOf(100);    // "100"
    String s2 = String.valueOf(3.14);   // "3.14"
    String s3 = String.valueOf(true);   // "true"
    
  2. Concatenation with Empty String:
    String s4 = "" + 100; // Evaluates to "100"
    
  3. Wrapper Class toString() Methods:
    String s5 = Integer.toString(100);  // "100"
    String s6 = Double.toString(3.14);  // "3.14"
    

5. Formatting Output: printf, String.format, and Escape Sequences

Oracle lists a dedicated objective under Working with the String Class: "format Strings using escape sequences including %d, %n, and %s." Two methods implement it, and they take the identical arguments:

  • System.out.printf(String format, Object... args) — writes the formatted text straight to the console and returns the PrintStream. Nothing is stored.
  • String.format(String format, Object... args) — builds and returns a new String without printing anything. Use this when you need to store, log, or concatenate the result.
int quantity = 7;
double price = 12.5;
String product = "Widget";

System.out.printf("%d x %s @ $%.2f%n", quantity, product, price);
// Console: 7 x Widget @ $12.50

String receipt = String.format("%d x %s", quantity, product);
System.out.println(receipt); // Prints: 7 x Widget

The Format Specifiers Tested on 1Z0-811

Every specifier begins with a percent sign, and the arguments are consumed left to right in declaration order.

SpecifierAcceptsProducesExampleOutput
%dIntegral types (byte, short, int, long, and their wrappers)Decimal integerString.format("%d", 42)42
%sAny type, including nullThe value's String representationString.format("%s", true)true
%ffloat / doubleDecimal floating point, 6 decimal places by defaultString.format("%f", 3.5)3.500000
%.2ffloat / doubleFloating point rounded to 2 decimalsString.format("%.2f", 3.567)3.57
%n(takes no argument)The platform line separatorSystem.out.printf("A%nB")A, newline, B
%%(takes no argument)A literal percent signString.format("%d%%", 15)15%
%bAny typetrue for any non-null value, false for nullString.format("%b", "hi")true
%cchar or an int code pointA single characterString.format("%c", 65)A

Width and Alignment

Placing a number between the % and the conversion character sets a minimum field width, right-justified by default. A minus sign left-justifies:

System.out.printf("|%10s|%n", "Java");   // |      Java|  (right-justified in 10 columns)
System.out.printf("|%-10s|%n", "Java");  // |Java      |  (left-justified in 10 columns)
System.out.printf("|%5d|%n", 42);        // |   42|

%n versus \n: The Portability Distinction

[!IMPORTANT] A high-yield exam contrast. %n is a format specifier that expands to whatever line separator the host operating system uses — \n on Linux and macOS, \r\n on Windows. \n is an escape sequence inside the string literal itself and always emits a single line-feed character on every platform. %n is therefore the portable choice inside printf and String.format, while \n is what you use inside an ordinary string literal passed to println or concatenation. Note also that %n consumes no argument — supplying one for it silently shifts your remaining arguments out of alignment.

Escape Sequences Inside String Literals

Escape sequences are resolved by the compiler when it reads the literal, so they work in every string, not just formatted ones:

EscapeMeaning
\nLine feed (newline)
\tHorizontal tab
\"A literal double quote inside a "..." literal
\'A literal single quote inside a '...' char literal
\\A single literal backslash
\u0041The Unicode character with hexadecimal code 0041 (the letter A)
System.out.println("Name:\tAda\nRole:\t\"Engineer\"");
// Console:
// Name:   Ada
// Role:   "Engineer"

System.out.println("C:\\Users\\student");  // Prints: C:\Users\student

The Type-Mismatch Trap

[!WARNING] %d will not accept a floating-point value. Format conversions are checked at runtime, not compile time, so a mismatched specifier compiles cleanly and then throws:

System.out.printf("%d", 3.14); // Compiles! Throws java.util.IllegalFormatConversionException at runtime

The safe conversions are %d for integral values, %f for floating-point values, and %s for absolutely anything (including null, which %s renders as the four-character text null rather than throwing). Supplying fewer arguments than the format string demands throws java.util.MissingFormatArgumentException; supplying extra arguments is silently ignored.

Loading diagram...
String Immutability vs. StringBuilder Buffer Mutation
Test Your Knowledge

What is the output of the following Java program?

String phrase = "Certification";
// Index:        0123456789012
String sub = phrase.substring(4, 9);
System.out.println(sub + " length: " + sub.length());

A
B
C
D
Test Your Knowledge

Examine the following code snippet using StringBuilder:

StringBuilder sb = new StringBuilder("Java");
sb.append(" 8");
sb.insert(4, " SE");
sb.reverse();
System.out.println(sb);
What is the output printed to standard output?

A
B
C
D
Test Your Knowledge

What happens when the following code is executed?

String sNum = "42";
String sBool = "FaLsE";
int num = Integer.parseInt(sNum);
boolean flag = Boolean.parseBoolean(sBool);
System.out.println((num + 8) + " : " + flag);

A
B
C
D
Test Your Knowledge

What is the result of executing the following Java statements?

int units = 3;
double cost = 4.5;
System.out.printf("%d items cost $%.2f%n", units, cost);
System.out.printf("%d", cost);

A
B
C
D