Java String Methods Cheat Sheet
1. Basic Info
Method Use Example
length() Get number of characters "Java".length() -> 4
charAt(index) Get character at position "Java".charAt(1) -> 'a'
toCharArray() Convert to char array "abc".toCharArray()
concat(str) Join two strings "Hello".concat(" World") -> Hello World
2. Comparison
Method Use Example
equals() Compare (case-sensitive) "Java".equals("Java") -> true
equalsIgnoreCase() Compare ignoring case "java".equalsIgnoreCase("JAVA") -> true
compareTo() Lexicographic compare "A".compareTo("B") -> -1
compareToIgnoreCase() Case-insensitive comparison "a".compareToIgnoreCase("A") -> 0
3. Search
Method Use Example
contains(str) Check if contains substring "abc".contains("b") -> true
startsWith(str) Starts with substring? "Java".startsWith("J")
endsWith(str) Ends with substring? "code".endsWith("e")
indexOf(str) First occurrence index "aabb".indexOf("b") -> 2
lastIndexOf(str) Last occurrence index "aabba".lastIndexOf("a") -> 4
4. Substring & Replace
Method Use Example
substring(start) From start to end "Hello".substring(2) -> "llo"
substring(start, end) From start to end-1 "Hello".substring(1,4) -> "ell"
replace(a, b) Replace char/string "pop".replace('p','t') -> "tot"
replaceAll(regex, rep) Replace all matches "abc123".replaceAll("[0-9]", "*")
replaceFirst(regex, rep) Replace first match "1-2-3".replaceFirst("-", ":") -> "1:2-3"
5. Trimming & Case
Method Use Example
trim() Remove leading/trailing spaces " abc ".trim() -> "abc"
strip() Unicode-aware trim " abc ".strip() -> "abc"
stripLeading() Remove leading spaces " abc ".stripLeading()
stripTrailing() Remove trailing spaces " abc ".stripTrailing()
toUpperCase() To uppercase "java".toUpperCase() -> "JAVA"
toLowerCase() To lowercase "JAVA".toLowerCase() -> "java"
6. Split, Join & Format
Method Use Example
split(regex) Split by pattern "a,b,c".split(",")
Java String Methods Cheat Sheet
join(delimiter, parts) Join with delimiter String.join("-", "a", "b")
valueOf(x) Convert to string String.valueOf(10) -> "10"
format(fmt, args...) Formatted string String.format("Hi %s", "Tom")
intern() Share from string pool "Hello".intern()