Strings

A String in Java is:

  • An immutable sequence of characters
  • Stored in String Pool for memory optimization
  • Represented internally as a char[] (Java 8) or byte[] with coder (Java 9+)

Once created, a String cannot be modified.


Why String is Immutable?

  • Security (used in URLs, DB connections, class loading)
  • Thread safety
  • Caching & String Pool optimization
  • HashCode caching (important for HashMap)

String Pool

  • String literals go to String Pool
  • new String("abc") creates object in heap
  • intern() moves string to pool
String a = "java";
String b = "java";          // same reference
String c = new String("java"); // different reference

Common String Operations

๐Ÿ”น Length & Access

  • length()
  • charAt(int index)
  • substring(int begin)
  • substring(int begin, int end)

๐Ÿ”น Comparison

  • equals()
  • equalsIgnoreCase()
  • compareTo()
  • compareToIgnoreCase()

โš ๏ธ Never use == for content comparison.

๐Ÿ”น Searching

  • contains()
  • indexOf()
  • lastIndexOf()
  • startsWith()
  • endsWith()

๐Ÿ”น Modification (Creates New String)

  • toUpperCase()
  • toLowerCase()
  • trim()
  • strip() // Java 11+
  • stripLeading()
  • stripTrailing()
  • replace()
  • replaceAll()
  • replaceFirst()

๐Ÿ”น Splitting & Joining

  • split()
  • String.join()

Java 11+ String Enhancements (Very Important)

  • isBlank() // checks whitespace only
  • lines() // stream of lines
  • repeat(int n)
  • strip() // Unicode-aware trim

Example:

โ€ โ€œ.isBlank(); // true

โ€œab\ncdโ€.lines();

Java 12+ / 15+ Updates (FYI)

  • Compact Strings (internal optimization)

  • Text Blocks (โ€œโ€โ€ โ€œโ€โ€) โ€“ not a String method, but related

String json = """
{
"name": "Java"
}
""";

Mutable Alternatives

๐Ÿ”น StringBuilder

  • Mutable
  • Faster
  • Not thread-safe

๐Ÿ”น StringBuffer

  • Mutable
  • Thread-safe
  • Slower

Use StringBuilder in almost all cases.


Table of contents


This site uses Just the Docs, a documentation theme for Jekyll.