The String Class & Common Methods
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.
Creating Strings
The simplest way is a string literal, but you can also use the constructor:
==. 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.
substring()
substring(beginIndex) returns everything from that index to the end. substring(beginIndex, endIndex) returns characters from beginIndex up to — but not including — endIndex.
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.
contains() when you only need a yes/no answer — it is more readable than checking whether indexOf() returned -1.
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.
. 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.
equals() and equalsIgnoreCase()
Use equals() for a case-sensitive comparison and equalsIgnoreCase() when case should not matter.
Other Handy Methods
trim()/strip()— remove leading and trailing whitespace. Preferstrip()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 aString.
Putting It All Together
Here is a small utility that parses a simple configuration line:
+ 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 ==.