Java Cheatsheet
Strings
Use this Java reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
String Basics
String is immutable — every operation returns a new String.
String s = "hello"; // string literal (interned/pooled) String s2 = new String("hello"); // new object — avoid; wastes memory String s3 = null; // reference can be null // Equality s.equals(s2) // true — compares content s == s2 // false for new String(), true for literals (pooled) s.equalsIgnoreCase("HELLO") // true
String Creation and Conversion
// From primitives / other types String.valueOf(42) // "42" String.valueOf(3.14) // "3.14" String.valueOf(true) // "true" String.valueOf('A') // "A" Integer.toString(42) // "42" "" + 42 // "42" (concatenation trick) // From char array char[] chars = {'h','e','l','l','o'}; String s = new String(chars); String s2 = String.valueOf(chars); // Parsing strings to primitives Integer.parseInt("42") Long.parseLong("999") Double.parseDouble("3.14") Boolean.parseBoolean("true") // only "true" (case-insensitive) → true
Length and Access
String s = "hello world"; s.length() // 11 s.isEmpty() // false (length == 0) s.isBlank() // false (Java 11+: length == 0 or all whitespace) s.charAt(0) // 'h' s.charAt(s.length()-1)// 'd' s.indexOf('o') // 4 (first occurrence) s.indexOf('o', 5) // 7 (start search from index 5) s.lastIndexOf('o') // 7 s.indexOf("world") // 6 s.lastIndexOf("l") // 9
Substrings
String s = "hello world"; s.substring(6) // "world" (from index 6 to end) s.substring(0, 5) // "hello" (indices [0,5) — end is exclusive) s.subSequence(0, 5) // CharSequence "hello"
Searching and Testing
String s = "Hello, World!"; s.contains("World") // true s.startsWith("Hello") // true s.startsWith("World", 7) // true (from index 7) s.endsWith("!") // true s.matches("Hello.*") // true (full regex match)
Comparison
"apple".equals("apple") // true "apple".equalsIgnoreCase("APPLE") // true "apple".compareTo("banana") // negative (apple < banana) "apple".compareToIgnoreCase("APPLE") // 0
Case Conversion
"hello".toUpperCase() // "HELLO" "HELLO".toLowerCase() // "hello" // Locale-sensitive variants (important for Turkish, German, etc.): "hello".toUpperCase(Locale.ENGLISH) "İSTANBUL".toLowerCase(Locale.forLanguageTag("tr"))
Trimming and Stripping
" hello ".trim() // "hello" (removes ASCII whitespace only) " hello ".strip() // "hello" (Java 11+: removes Unicode whitespace) " hello ".stripLeading() // "hello " (Java 11+) " hello ".stripTrailing()// " hello" (Java 11+)
Replacing
String s = "banana"; s.replace('a', 'o') // "bonono" (char) s.replace("an", "en") // "benena" (string, all occurrences) s.replaceFirst("a", "x") // "xanana" (first occurrence, regex) s.replaceAll("[aeiou]", "*") // "b*n*n*" (regex, all) "hello world".replace("world", "Java") // "hello Java"
Splitting and Joining
// Split "a,b,c".split(",") // ["a","b","c"] "a,b,,c".split(",") // ["a","b","","c"] (empty string between commas) "a,b,,c".split(",", -1) // keeps trailing empty strings "a,b,c".split(",", 2) // ["a","b,c"] (limit max parts) "one two three".split("\\s+") // ["one","two","three"] (any whitespace) // Join String.join(", ", "a","b","c") // "a, b, c" String.join("-", List.of("2026","06","13")) // "2026-06-13" String.join("\n", lines)
String.format and Formatted
String s = String.format("Hello %s, you are %d years old", "Alice", 30); String s2 = "Pi is %.4f".formatted(Math.PI); // Java 15+ // Common format specifiers // %s string %n newline (platform-independent) // %d decimal int %f floating-point // %c char %b boolean // %x hex (lowercase) %X hex (uppercase) // %o octal %e scientific notation // %-10s left-align in 10-char field // %10s right-align in 10-char field // %05d zero-pad to width 5 // %.2f 2 decimal places // %,d number with thousands separator (e.g. 1,000,000)
Char Array Operations
String s = "hello"; char[] arr = s.toCharArray(); // {'h','e','l','l','o'} arr[0] = 'H'; String modified = new String(arr); // "Hello" // Iterate chars for (char c : s.toCharArray()) { System.out.println(c); } // Java 8+ streams over chars s.chars() // IntStream of char values .filter(Character::isLetter) .mapToObj(c -> String.valueOf((char) c)) .forEach(System.out::print);
StringBuilder — Mutable String Buffer
Use when building strings in loops (avoids creating many intermediate String objects).
StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(", "); sb.append("World"); sb.append('!'); sb.append(42); // appends "42" sb.insert(5, " there"); // insert at index sb.delete(5, 11); // remove [5,11) sb.deleteCharAt(0); // remove single char sb.replace(0, 5, "Hi"); // replace [0,5) with "Hi" sb.reverse(); sb.setCharAt(0, 'H'); // mutate char at index sb.indexOf("World"); sb.toString(); // convert to String // Length and capacity sb.length() // current number of chars sb.capacity() // current buffer capacity (auto-grows) sb.charAt(0) // char at index sb.setLength(5) // truncate (or extend with '\0') to length 5 // Chaining String result = new StringBuilder() .append("Hello") .append(' ') .append("World") .toString();
StringBuffer
Thread-safe version of StringBuilder. Same API, synchronized. Prefer StringBuilder in single-threaded code.
StringBuffer sbf = new StringBuffer("hello"); sbf.append(" world").reverse();
String Pool / Interning
String a = "hello"; // interned String b = "hello"; // same pooled instance a == b // true (same pool object) String c = new String("hello"); a == c // false (different object) a.equals(c) // true (same content) String d = c.intern(); // returns pooled instance a == d // true
Regex with Strings
"hello123".matches("[a-z]+\\d+") // true (whole string) "hello".matches("\\d+") // false "one1two2three".replaceAll("\\d", "") // "onetwothree" "one1two2three".replaceFirst("\\d","_") // "one_two2three" "a1b2c3".split("\\d") // ["a","b","c",""] // Compile Pattern for reuse (more efficient) import java.util.regex.*; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher("abc123def456"); while (matcher.find()) { System.out.println(matcher.group()); // "123", then "456" matcher.start(); // start index of match matcher.end(); // end index (exclusive) } matcher.matches() // whole string matches matcher.find() // find next match matcher.group(0) // full match matcher.group(1) // first capture group matcher.replaceAll("N") // replace all matches Pattern.matches("\\d+", "123") // quick one-off test
Text Blocks (Java 15+)
Multi-line string literals. Automatically strips common leading whitespace.
String json = """ { "name": "Alice", "age": 30 } """; String html = """ <html> <body>Hello</body> </html> """; // Escape sequences still work String s = """ Line 1\nLine 2 Tab\there """; // Trailing space: use \s to preserve trailing whitespace on a line // Line continuation: use \ at end of line to avoid newline String longLine = """ This is a very \ long line. """;
Useful String Utilities (java.util)
// StringJoiner StringJoiner sj = new StringJoiner(", ", "[", "]"); sj.add("Alice"); sj.add("Bob"); sj.add("Carol"); sj.toString() // "[Alice, Bob, Carol]" sj.setEmptyValue("(none)"); // Collectors.joining List<String> names = List.of("Alice","Bob","Carol"); names.stream().collect(Collectors.joining(", ")) // "Alice, Bob, Carol" names.stream().collect(Collectors.joining(", ","[","]")) // "[Alice, Bob, Carol]"
Common String Gotchas
// NullPointerException String s = null; s.length(); // NPE — use Objects.requireNonNullElse or null check // Comparing with == instead of equals String a = new String("hi"); String b = new String("hi"); a == b // false — always use .equals() // Integer parsing failure Integer.parseInt("42.0"); // NumberFormatException (not an int) Integer.parseInt(""); // NumberFormatException // Regex special chars must be escaped "1.2".split(".") // [] — '.' is regex "any char", splits everything "1.2".split("\\.") // ["1","2"] — escaped literal dot // Modifying chars — String is immutable String s = "hello"; s.charAt(0) = 'H'; // compile error — charAt returns, doesn't set // Use StringBuilder or toCharArray()