[Go to site: main page, start]

0% found this document useful (0 votes)
7 views5 pages

Java String Methods

The document provides an overview of Java's String, StringBuffer, and StringBuilder classes, highlighting their characteristics and built-in methods. String is immutable, while StringBuffer is mutable and thread-safe, and StringBuilder is mutable but faster for single-threaded use. A quick comparison of their features, performance, and common use cases is also included.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

Java String Methods

The document provides an overview of Java's String, StringBuffer, and StringBuilder classes, highlighting their characteristics and built-in methods. String is immutable, while StringBuffer is mutable and thread-safe, and StringBuilder is mutable but faster for single-threaded use. A quick comparison of their features, performance, and common use cases is also included.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

String Reference String · StringBuffer · StringBuilder Bu

String — immutable sequence of characters. Every modification creates a new object.


StringBuffer — mutable, thread-safe (synchronized). Use in multi-threaded code.
StringBuilder — mutable, not thread-safe but faster. Preferred in single-threaded code.

1. [Link] — Built-in Methods


String objects are immutable. Every method returns a new String; the original is unchanged. String literals are
automatically interned in the string pool.

Method Description Example

length() Returns length of the string "hello".length() → 5

charAt(i) Returns char at index i "Java".charAt(1) → 'a'

indexOf(str) First index of str, -1 if not found "hello".indexOf("l") → 2

lastIndexOf(str) Last occurrence index "hello".lastIndexOf("l") → 3

substring(i) Substring from index i to end "hello".substring(2) → "llo"

substring(i,j) Substring from i (inclusive) to j "hello".substring(1,4) → "ell"


(exclusive)

toLowerCase() Converts to lower case "JAVA".toLowerCase() → "java"

toUpperCase() Converts to upper case "java".toUpperCase() → "JAVA"

trim() Removes leading/trailing whitespace " hi ".trim() → "hi"

strip() Like trim() but Unicode-aware (Java " hi ".strip() → "hi"


11+)

replace(old,new) Replaces all occurrences of old with "aabbcc".replace("b","x") → "aaxxcc"


new

replaceAll(regex,rep) Replace using regex pattern "a1b2".replaceAll("[0-9]","#") →


"a#b#"

replaceFirst(regex,re Replace first regex match "a1b2".replaceFirst("[0-9]","#") →


p) "a#b2"

contains(seq) True if string contains the sequence "hello".contains("ell") → true


Method Description Example

startsWith(prefix) True if starts with prefix "Java".startsWith("Ja") → true

endsWith(suffix) True if ends with suffix "Java".endsWith("va") → true

equals(obj) Case-sensitive equality check "abc".equals("abc") → true

equalsIgnoreCase(s) Case-insensitive equality check "ABC".equalsIgnoreCase("abc") → true

compareTo(s) Lexicographic comparison; 0 if equal "a".compareTo("b") → -1

split(regex) Split string by regex; returns String[] "a,b,c".split(",") → ["a","b","c"]

join(delim,…) Join strings with a delimiter (static) [Link]("-","a","b") → "a-b"

concat(s) Appends s to the string "Hello".concat(" World") → "Hello


World"

isEmpty() True if length == 0 "".isEmpty() → true

isBlank() True if blank/whitespace (Java 11+) " ".isBlank() → true

toCharArray() Converts string to char[] "hi".toCharArray() → ['h','i']

valueOf(x) Converts x to String (static) [Link](42) → "42"

format(fmt,…) Formatted string (static) [Link]("Hi %s",name)

matches(regex) True if whole string matches regex "12".matches("[0-9]+") → true

intern() Returns canonical representation from "hello".intern()


pool

chars() Returns IntStream of char values (Java "ab".chars() → IntStream


8+)

repeat(n) Repeats string n times (Java 11+) "ab".repeat(3) → "ababab"

stripLeading() Removes leading whitespace (Java " hi ".stripLeading() → "hi "


11+)

stripTrailing() Removes trailing whitespace (Java " hi ".stripTrailing() → " hi"


11+)

lines() Stream of lines (Java 11+) "a\nb".lines() → Stream["a","b"]

codePointAt(i) Unicode code point at index i "A".codePointAt(0) → 65

hashCode() Returns hash code of the string "hello".hashCode() → int

* Methods marked Java 11+ require JDK 11 or later. Java 8+ methods require JDK 8+.
2. [Link] — Built-in Methods
StringBuffer is mutable and thread-safe (all public methods are synchronized). Use it when multiple threads share a
mutable character sequence. Constructors: StringBuffer(), StringBuffer(int capacity),
StringBuffer(String str).

Shared Methods (StringBuffer & StringBuilder)

Method Description Example

append(x) Appends x (any type) to the sequence [Link]("Hi").append(42)

insert(i, x) Inserts x at index i [Link](2, "XX")

delete(i, j) Deletes chars from i to j-1 [Link](1, 3)

deleteCharAt(i) Deletes char at index i [Link](0)

replace(i,j,str) Replaces chars i to j-1 with str [Link](1, 3, "ZZ")

reverse() Reverses the character sequence [Link]() // "abc" → "cba"

indexOf(str) First index of str [Link]("lo")

lastIndexOf(str) Last index of str [Link]("o")

charAt(i) Returns char at index i [Link](2)

setCharAt(i,c) Sets char at index i to c [Link](0, 'H')

length() Current length of sequence [Link]()

capacity() Current allocated capacity [Link]() // default 16

ensureCapacity(min) Ensures capacity >= min [Link](50)

substring(i) Substring from i to end [Link](3)

substring(i,j) Substring from i to j-1 [Link](1, 4)

toString() Converts to immutable String [Link]()

codePointAt(i) Unicode code point at index i [Link](0)

indexOf(str,from) Search starting from fromIndex [Link]("a", 2)

StringBuffer-specific Behaviour

Method Description Example

synchronized methods All methods are synchronized (thread-safe) new StringBuffer("safe")


3. [Link] — Built-in Methods
StringBuilder has an identical API to StringBuffer but is not synchronized, making it faster for single-threaded
scenarios. It was introduced in Java 5 as the preferred replacement for StringBuffer in non-concurrent code.

All Shared Methods (same as StringBuffer above)

Method Description Example

append(x) Appends x (any type) to the sequence [Link]("Hi").append(42)

insert(i, x) Inserts x at index i [Link](2, "XX")

delete(i, j) Deletes chars from i to j-1 [Link](1, 3)

deleteCharAt(i) Deletes char at index i [Link](0)

replace(i,j,str) Replaces chars i to j-1 with str [Link](1, 3, "ZZ")

reverse() Reverses the character sequence [Link]() // "abc" → "cba"

indexOf(str) First index of str [Link]("lo")

lastIndexOf(str) Last index of str [Link]("o")

charAt(i) Returns char at index i [Link](2)

setCharAt(i,c) Sets char at index i to c [Link](0, 'H')

length() Current length of sequence [Link]()

capacity() Current allocated capacity [Link]() // default 16

ensureCapacity(min) Ensures capacity >= min [Link](50)

substring(i) Substring from i to end [Link](3)

substring(i,j) Substring from i to j-1 [Link](1, 4)

toString() Converts to immutable String [Link]()

codePointAt(i) Unicode code point at index i [Link](0)

indexOf(str,from) Search starting from fromIndex [Link]("a", 2)

StringBuilder-specific Behaviour
Method Description Example

Non-synchronized Same API as StringBuffer but new StringBuilder("fast")


unsynchronized — faster in single-threaded
use

4. Quick Comparison

Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable

Thread-safe Yes (immutable) Yes (sync) No

Performance Slowest (concat) Medium Fastest

Memory Pool / heap Heap Heap

Since Java 1.0 1.0 1.5

Common use Literals, keys Multi-thread Single-thread

Reference covers Java SE 17 LTS. Methods introduced in later versions are noted inline. All classes reside in the [Link]
package (auto-imported).

You might also like