Methods, Arrays & Strings

The String Class & Common Methods

15 min Lesson 8 of 14

The String Class & Common Methods

Strings are among the most frequently used types in any Java program. In Java, a String is not a primitive — it is a full object backed by the java.lang.String class, and it comes packed with methods that cover nearly every text-processing task you will ever need.

String Immutability — the Most Important Rule

Once a String object is created, its content cannot be changed. Every method that appears to "modify" a string actually returns a brand-new String object; the original is left untouched.

String greeting = "Hello"; greeting.toUpperCase(); // does nothing useful — result is discarded System.out.println(greeting); // still prints: Hello String upper = greeting.toUpperCase(); // correct: capture the new object System.out.println(upper); // prints: HELLO
Why immutability? Immutable strings are safe to share across multiple parts of a program without unexpected side effects. Java also caches string literals in a string pool, so identical literals refer to the same object, saving memory. This only works because no one can mutate the shared object.

Creating Strings

The simplest way is a string literal, but you can also use the constructor:

String a = "Java"; // literal — stored in the string pool String b = new String("Java"); // explicit constructor — always a new heap object System.out.println(a.equals(b)); // true — same characters System.out.println(a == b); // false — different object references
Never compare strings with ==. The == operator checks whether two variables point to the same object in memory, not whether they contain the same text. Always use .equals() (case-sensitive) or .equalsIgnoreCase().

length() and charAt()

length() returns the number of characters. charAt(index) returns the character at a zero-based position.

String word = "Java"; System.out.println(word.length()); // 4 System.out.println(word.charAt(0)); // J System.out.println(word.charAt(3)); // a // iterate over every character for (int i = 0; i < word.length(); i++) { System.out.print(word.charAt(i) + " "); // J a v a }

substring()

substring(beginIndex) returns everything from that index to the end. substring(beginIndex, endIndex) returns characters from beginIndex up to — but not includingendIndex.

String text = "Learning Java"; System.out.println(text.substring(9)); // Java System.out.println(text.substring(0, 8)); // Learning

indexOf() and lastIndexOf()

indexOf(str) returns the index of the first occurrence of a substring, or -1 if not found. lastIndexOf(str) finds the last occurrence.

String sentence = "to be or not to be"; System.out.println(sentence.indexOf("be")); // 3 System.out.println(sentence.lastIndexOf("be")); // 16 System.out.println(sentence.indexOf("Java")); // -1 (not found)
Checking for presence: use contains() when you only need a yes/no answer — it is more readable than checking whether indexOf() returned -1.
if (sentence.contains("not")) { System.out.println("Found it!"); }

split()

split(regex) breaks the string into an array wherever the pattern matches. The pattern is a regular expression, but for simple delimiters like a comma or space you can pass them as-is.

String csv = "Alice,Bob,Carol,Dave"; String[] names = csv.split(","); for (String name : names) { System.out.println(name); } // Alice // Bob // Carol // Dave
Splitting on a dot: the dot . is a regex wildcard that matches any character. To split on a literal dot, escape it: split("\\.").

replace() and replaceAll()

replace(old, new) substitutes every occurrence of a character or literal substring. replaceAll(regex, replacement) does the same with a regular-expression pattern.

String path = "C:\\Users\\alice\\Documents"; String unixPath = path.replace("\\", "/"); System.out.println(unixPath); // C:/Users/alice/Documents String noDigits = "p4ssw0rd".replaceAll("\\d", "*"); System.out.println(noDigits); // p*ssw*rd

equals() and equalsIgnoreCase()

Use equals() for a case-sensitive comparison and equalsIgnoreCase() when case should not matter.

String input = "Admin"; System.out.println(input.equals("admin")); // false System.out.println(input.equalsIgnoreCase("admin")); // true // good practice: put the known literal on the left to avoid NullPointerException System.out.println("admin".equalsIgnoreCase(input)); // true — safe even if input is null

Other Handy Methods

  • trim() / strip() — remove leading and trailing whitespace. Prefer strip() on Java 11+ because it is Unicode-aware.
  • toUpperCase() / toLowerCase() — change case.
  • startsWith(prefix) / endsWith(suffix) — boolean checks.
  • isEmpty() — true if length is 0. isBlank() (Java 11+) — true if empty or only whitespace.
  • String.valueOf(x) — converts any primitive to a String.

Putting It All Together

Here is a small utility that parses a simple configuration line:

String line = " host = localhost:8080 "; String trimmed = line.strip(); // "host = localhost:8080" String[] parts = trimmed.split("=", 2); // ["host ", " localhost:8080"] String key = parts[0].strip(); // "host" String value = parts[1].strip(); // "localhost:8080" System.out.println("Key: " + key); System.out.println("Value: " + value); // further break the value on ":" String host = value.substring(0, value.indexOf(":")); String port = value.substring(value.indexOf(":") + 1); System.out.println("Host: " + host + ", Port: " + port); // Host: localhost, Port: 8080
String concatenation in loops is slow because each + creates a new object. When you need to build a string step by step inside a loop, use StringBuilder instead — that is the topic of the very next lesson.

Summary

Strings in Java are immutable objects. Always capture the result of any String method — the original is never modified. Key methods you will use constantly: length(), charAt(), substring(), indexOf(), split(), replace(), and equals(). Compare strings with .equals(), not ==.