What is String in Java - Java String Methods & Type (Examples)
A String in Java is an object that represents a sequence of characters, and it is one of the most frequently used classes in the entire language. Unlike primitive types, String is a class defined in java.lang, which means every string comes with a rich set of built-in methods for searching, comparing, and transforming text.
Why Strings Are Immutable
Once a String object is created in Java, its value can never be changed. Any operation that appears to "modify" a string, such as concatenation, actually creates a brand-new String object in memory. This immutability makes strings safe to share across threads and enables Java's String Pool, which reuses identical string literals to save memory.
Commonly Used String Methods
length()— returns the number of characters in the stringcharAt(index)— returns the character at a specific positionsubstring(start, end)— extracts a portion of the stringequals()andequalsIgnoreCase()— compare string contenttoUpperCase()/toLowerCase()— changes letter casingtrim()— removes leading and trailing whitespacesplit(regex)— breaks a string into an array based on a delimiterreplace()— swaps characters or substrings with new ones
String vs StringBuilder vs StringBuffer
Because String objects are immutable, repeatedly modifying strings in a loop (like building a long piece of text) creates unnecessary objects and hurts performance. StringBuilder solves this by being mutable and unsynchronized, making it fast for single-threaded use. StringBuffer offers the same mutability but is synchronized, making it thread-safe at a small performance cost.
Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.