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.
2.4 String Methods, StringBuilder Operations, and Type Parsing
Quick Summary: Fluent string manipulation requires mastering core
Stringmethods, string concatenation evaluation precedence, mutableStringBuilderoperations, and parsing utilities.Stringmethods operate with 0-based indexing and always return new instances. For heavy repetitive modifications,StringBuilderavoids memory churn by altering an internal character buffer in place. Converting text to primitives utilizes wrapper methods likeInteger.parseInt()andDouble.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.lengthfield without parentheses!).char charAt(int index): Returns the character at the specified 0-based index. If the index is negative or >= length(), the JVM throwsStringIndexOutOfBoundsException.int indexOf(String str)/int indexOf(char ch): Returns the 0-based index of the first occurrence of the target character or substring. Returns-1if not found.int indexOf(String str, int fromIndex): Searches forward starting atfromIndex.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): Returnstrueif the sequence appears anywhere within the string.boolean isEmpty(): Returnstrueif and only iflength() == 0.
String Manipulation Methods (Always Return New Strings!)
String substring(int beginIndex): Returns a new string extracting characters starting frombeginIndexthrough the end of the string.String substring(int beginIndex, int endIndex):- CRITICAL EXAM RULE: The substring begins at
beginIndex(inclusive) and extends up toendIndex(exclusive). - The length of the resulting substring is always endIndex - beginIndex.
- If
beginIndex == endIndex, it returns an empty string"". - If
beginIndex < 0,endIndex > length(), orbeginIndex > endIndex, it throwsStringIndexOutOfBoundsException.
- CRITICAL EXAM RULE: The substring begins at
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 ofoldCharis replaced withnewChar.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 tothis(the sameStringBuilderinstance).StringBuilder insert(int offset, ...): Inserts data at the specified index, shifting existing characters to the right. Returnsthis.StringBuilder delete(int start, int end): Removes characters fromstart(inclusive) up toend(exclusive). Returnsthis.StringBuilder deleteCharAt(int index): Removes the character at the specified index. Returnsthis.StringBuilder reverse(): Reverses the character sequence in place. Returnsthis.String toString(): Constructs and returns a standard immutableStringcontaining 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
Stringclass,StringBuilderdoes NOT override theequals()method fromjava.lang.Object. Therefore, invokingsb1.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 primitiveint.Double.parseDouble(String s): Parses a string into a primitivedouble.Long.parseLong(String s): Parses a string into a primitivelong.Boolean.parseBoolean(String s): Parses a string into a primitiveboolean.
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
trueif and only if the argument is non-null and equals"true"ignoring case ("true","True","TRUE"). - Returns
falsefor any other input, including"false","yes","1", random gibberish, empty strings, andnull.
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:
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"- Concatenation with Empty String:
String s4 = "" + 100; // Evaluates to "100" - 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 thePrintStream. Nothing is stored.String.format(String format, Object... args)— builds and returns a newStringwithout 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.
| Specifier | Accepts | Produces | Example | Output |
|---|---|---|---|---|
%d | Integral types (byte, short, int, long, and their wrappers) | Decimal integer | String.format("%d", 42) | 42 |
%s | Any type, including null | The value's String representation | String.format("%s", true) | true |
%f | float / double | Decimal floating point, 6 decimal places by default | String.format("%f", 3.5) | 3.500000 |
%.2f | float / double | Floating point rounded to 2 decimals | String.format("%.2f", 3.567) | 3.57 |
%n | (takes no argument) | The platform line separator | System.out.printf("A%nB") | A, newline, B |
%% | (takes no argument) | A literal percent sign | String.format("%d%%", 15) | 15% |
%b | Any type | true for any non-null value, false for null | String.format("%b", "hi") | true |
%c | char or an int code point | A single character | String.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.
%nis a format specifier that expands to whatever line separator the host operating system uses —\non Linux and macOS,\r\non Windows.\nis an escape sequence inside the string literal itself and always emits a single line-feed character on every platform.%nis therefore the portable choice insideprintfandString.format, while\nis what you use inside an ordinary string literal passed toprintlnor concatenation. Note also that%nconsumes 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:
| Escape | Meaning |
|---|---|
\n | Line feed (newline) |
\t | Horizontal tab |
\" | A literal double quote inside a "..." literal |
\' | A literal single quote inside a '...' char literal |
\\ | A single literal backslash |
\u0041 | The 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]
%dwill 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 runtimeThe safe conversions are
%dfor integral values,%ffor floating-point values, and%sfor absolutely anything (includingnull, which%srenders as the four-character textnullrather than throwing). Supplying fewer arguments than the format string demands throwsjava.util.MissingFormatArgumentException; supplying extra arguments is silently ignored.
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());
Examine the following code snippet using StringBuilder:
What is the output printed to standard output?StringBuilder sb = new StringBuilder("Java");
sb.append(" 8");
sb.insert(4, " SE");
sb.reverse();
System.out.println(sb);
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);
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);