beginnerFree

String Methods

Deep dive - trim, replace, split & more

String Methods

String is immutable - the original is never modified. Transform methods (trim/replace) return new strings; query methods return booleans; split returns an array.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:25

The Big Picture

String methods transform, search, and extract text. Strings are immutable: methods never change the receiver.

  • length(), charAt(), substring() - basics
  • contains(), indexOf(), startsWith() - searching
  • toUpperCase(), trim(), replace() - transforms

String has 60+ methods - learn the top 10, look up the rest.

How It Works

Simple methods are O(n) or better; regex methods cost more.

  • substring() creates a new String (since Java 7u6)
  • split() uses regex - can be slow for simple delimiters
  • matches() compiles regex each call - cache Pattern
  • join() for delimited text; repeated assembly use StringBuilder
  • chars() returns IntStream for functional processing

In the Java Landscape

String methods grew with each Java version.

  • Java 8: String.join() for joining with delimiter
  • Java 11: strip() (Unicode-aware), isBlank(), repeat()
  • Java 12: indent(), transform()
  • Apache StringUtils fills gaps: null-safe, padding, abbreviation
  • Regex: Pattern and Matcher for complex text processing

Pitfalls and Best Practices

  • Use strip() not trim() (handles Unicode whitespace)
  • equalsIgnoreCase() for case-insensitive comparison
  • isEmpty() checks length 0; isBlank() checks whitespace only
  • Chain carefully - null at any point throws NPE
  • Cache compiled Pattern objects for repeated regex use
  • Use replace() for literal, replaceAll() for regex
#java#fundamentals#strings