Strings in Java
Learn Strings in Java in detail, including String creation, immutability, String Pool, comparison, important methods, searching, extracting, modifying, formatting, StringBuilder, StringBuffer, performance, text blocks, and real-world string processing.
Introduction
Strings are among the most frequently used objects in Java. Names, email addresses, passwords, messages, file paths, URLs, search queries, JSON data, database values, and user input are commonly represented as strings.
public class Main {
public static void main(
String[] args
) {
String name = "Aarav";
String message =
"Welcome to Java";
System.out.println(name);
System.out.println(message);
}
}Although a String may appear similar to a primitive value, String is actually a class. Every string value is an object with methods for searching, comparing, extracting, replacing, splitting, formatting, and processing text.
- What a String is.
- Why strings are important.
- How to create strings.
- The difference between string literals and new String().
- Why String is a class.
- Why String objects are immutable.
- Why immutability is useful.
- What the String Pool is.
- How string references work.
- How to find string length.
- How to access individual characters.
- How string indexing works.
- How to loop through a string.
- How to convert a string to a character array.
- How to compare strings correctly.
- The difference between == and equals().
- How equalsIgnoreCase() works.
- How compareTo() works.
- How to check empty and blank strings.
- The difference between null, empty, and blank.
- How to change letter case.
- How to remove surrounding whitespace.
- How to search inside strings.
- How to find character and substring positions.
- How to check prefixes and suffixes.
- How to extract substrings.
- How to concatenate strings.
- How to join multiple strings.
- How to replace text.
- How to split strings.
- How regular expressions affect split() and replaceAll().
- How to repeat strings.
- How to test patterns.
- How to convert values to strings.
- How to format strings.
- How format specifiers work.
- How escape sequences work.
- How Unicode characters are represented.
- How text blocks work.
- What StringBuilder is.
- Why StringBuilder improves repeated modification.
- How to append, insert, replace, delete, and reverse text.
- How StringBuilder capacity works.
- What StringBuffer is.
- The difference between String, StringBuilder, and StringBuffer.
- How string operations affect performance.
- How to solve common string programming problems.
- How to validate text.
- Common string errors.
- String best practices.
What is a String?
A String is an object that represents a sequence of characters. In Java, strings are instances of the java.lang.String class.
String name = "Aarav";
String city = "Mumbai";
String language = "Java";
String message =
"Welcome to PrograMinds";"JAVA"
INDEX 0 1 2 3
CHARACTER J A V A
A STRING
IS AN ORDERED SEQUENCE
OF CHARACTERSWhy Strings are Important
User Data
Names, usernames, email addresses, addresses, and other text values are stored as strings.
Communication
Messages, notifications, logs, and application responses are represented as strings.
Web Development
URLs, HTML, JSON, HTTP headers, and form values frequently use strings.
File Processing
File names, paths, extensions, and file content are commonly processed as strings.
Databases
Text columns, SQL queries, and database results often involve string processing.
Search and Validation
Applications search, compare, validate, split, and transform text constantly.
Real-World Analogy
Think of a String as a fixed printed label. You can read the label, compare it, search within it, or create a new modified label, but the original printed label itself does not change.
ORIGINAL LABEL
"JAVA"
│
│ Request lowercase version
▼
NEW LABEL
"java"
ORIGINAL STILL EXISTS
"JAVA"
THIS REPRESENTS
STRING IMMUTABILITYCreating Strings
Java provides multiple ways to create String objects. The two most common approaches are string literals and the new keyword.
String first = "Java";
String second =
new String("Java");String Literals
String language = "Java";A string literal is text written inside double quotation marks. String literals can be reused through the String Pool.
String name = "Aarav";
String city = "Mumbai";
String empty = "";
String sentence =
"Java is powerful.";Creating Strings with the new Keyword
String language =
new String("Java");Using new explicitly creates a new String object instead of simply reusing the pooled literal reference.
String Literal vs new String()
String first = "Java";
String second = "Java";
String third =
new String("Java");STRING POOL
"Java"
▲
│
├──────── first
│
└──────── second
HEAP OBJECT
new String("Java")
▲
│
third- Use string literals for normal String creation.
- String literals allow pooled objects to be reused.
- Avoid new String(...) unless a separate object is intentionally required.
- In most application code, new String("text") is unnecessary.
Strings are Objects
String is not a primitive data type. It is a class, and string variables store references to String objects.
String language = "Java";
System.out.println(
language.length()
);
System.out.println(
language.toUpperCase()
);
System.out.println(
language.charAt(0)
);Because String is a class, String objects provide many useful methods.
The String Class
java.lang.String
COMMON CAPABILITIES
├── Measure Length
├── Access Characters
├── Compare Text
├── Search Text
├── Extract Text
├── Replace Text
├── Split Text
├── Change Case
├── Remove Whitespace
├── Format Values
├── Match Patterns
└── Convert ValuesThe String class belongs to java.lang, so it is automatically available without an explicit import.
String Immutability
String objects are immutable. After a String object is created, its character content cannot be changed.
String language = "Java";
language.toUpperCase();
System.out.println(language);JavaThe toUpperCase() method creates or returns another String value. It does not modify the original String object.
String language = "Java";
language =
language.toUpperCase();
System.out.println(language);JAVAWhy Strings are Immutable
Security
Important values such as file paths, class names, and network-related text cannot be unexpectedly changed through shared references.
String Pool
Shared pooled strings remain safe because one reference cannot modify the object for every other reference.
#️⃣ Stable Hashing
String hash values remain stable, making strings reliable keys in hash-based collections.
Thread Safety
Immutable objects can be shared between threads more safely because their state cannot change.
Optimization
The JVM can safely reuse and optimize immutable String objects.
Predictability
Methods do not unexpectedly change existing text values.
String Pool
The String Pool is a special storage area used by the JVM to reuse string literals with identical content.
String first = "Java";
String second = "Java";Both references can point to the same pooled String object because the literal content is identical.
How String Pool Works
String first = "Java";
JVM CHECKS STRING POOL
│
├── "Java" EXISTS?
│
└── NO
│
▼
CREATE "Java"
│
▼
first REFERENCES IT
String second = "Java";
JVM CHECKS STRING POOL
│
├── "Java" EXISTS?
│
└── YES
│
▼
REUSE EXISTING OBJECT
│
▼
second REFERENCES ITHeap and String Pool
String first = "Java";
String second = "Java";
String third =
new String("Java");first ──────┐
│
second ──────┴────► "Java"
STRING POOL
third ────────────► "Java"
SEPARATE OBJECTThe intern() Method
The intern() method returns the canonical pooled representation of a String.
String first = "Java";
String second =
new String("Java");
String third =
second.intern();
System.out.println(
first == third
);trueString References
String message = "Hello";
message =
message + " Java";BEFORE
message ─────► "Hello"
CONCATENATION
"Hello" + " Java"
│
▼
NEW STRING CREATED
"Hello Java"
AFTER
message ─────► "Hello Java"
ORIGINAL STRING
"Hello"
WAS NOT MODIFIEDString Length
The length() method returns the number of UTF-16 code units in a String.
String language = "Java";
System.out.println(
language.length()
);4- Arrays use the length field.
- Strings use the length() method.
- Array example: numbers.length
- String example: text.length()
Accessing Characters with charAt()
String language = "Java";
char first =
language.charAt(0);
char last =
language.charAt(
language.length() - 1
);
System.out.println(first);
System.out.println(last);J
aString Indexing
STRING
"JAVA"
CHARACTER
J A V A
INDEX
0 1 2 3
FIRST INDEX
0
LAST INDEX
length() - 1- The first valid index is 0.
- The last valid index is length() - 1.
- A negative index is invalid.
- An index equal to length() is invalid.
- Invalid character access causes StringIndexOutOfBoundsException.
Looping Through a String
String language = "Java";
for (
int i = 0;
i < language.length();
i++
) {
System.out.println(
language.charAt(i)
);
}J
a
v
aConverting a String to a Character Array
String language = "Java";
char[] characters =
language.toCharArray();
for (char character : characters) {
System.out.println(character);
}Comparing Strings
String comparison is one of the most important topics in Java because reference comparison and content comparison are different operations.
QUESTION 1
DO BOTH REFERENCES
POINT TO THE SAME OBJECT?
Use ==
QUESTION 2
DO BOTH STRINGS
CONTAIN THE SAME TEXT?
Use equals()The == Operator
For String references, the == operator checks whether both references point to the same object.
String first = "Java";
String second = "Java";
String third =
new String("Java");
System.out.println(
first == second
);
System.out.println(
first == third
);true
falseThe equals() Method
The equals() method compares the character content of two strings.
String first = "Java";
String second =
new String("Java");
System.out.println(
first.equals(second)
);true- Use equals() when comparing String content.
- Use == only when reference identity is intentionally being checked.
- Do not rely on String Pool behavior for application logic.
equalsIgnoreCase()
String first = "JAVA";
String second = "java";
System.out.println(
first.equalsIgnoreCase(second)
);truecompareTo()
The compareTo() method compares two strings lexicographically.
System.out.println(
"Apple".compareTo("Banana")
);
System.out.println(
"Java".compareTo("Java")
);
System.out.println(
"Python".compareTo("Java")
);NEGATIVE VALUE
First string comes before second
ZERO
Strings are equal
POSITIVE VALUE
First string comes after secondcompareToIgnoreCase()
int result =
"JAVA".compareToIgnoreCase(
"java"
);
System.out.println(result);0Checking Empty Strings
String text = "";
System.out.println(
text.length()
);0The isEmpty() Method
String first = "";
String second = " ";
System.out.println(
first.isEmpty()
);
System.out.println(
second.isEmpty()
);true
falseThe isBlank() Method
String first = "";
String second = " ";
String third = "Java";
System.out.println(
first.isBlank()
);
System.out.println(
second.isBlank()
);
System.out.println(
third.isBlank()
);true
true
falsenull vs Empty vs Blank
null
No String object reference
""
String exists
Length is 0
" "
String exists
Contains whitespace
Not empty
But blankif (
text == null
|| text.isBlank()
) {
System.out.println(
"Text is missing"
);
}Changing String Case
Java provides methods for creating uppercase and lowercase versions of strings.
toUpperCase()
String language = "Java";
String result =
language.toUpperCase();
System.out.println(result);JAVAtoLowerCase()
String language = "JAVA";
String result =
language.toLowerCase();
System.out.println(result);javaRemoving Surrounding Spaces
String text =
" Java ";Java provides trim(), strip(), stripLeading(), and stripTrailing() for removing surrounding whitespace.
trim()
String text =
" Java ";
System.out.println(
text.trim()
);Javastrip()
The strip() method removes leading and trailing Unicode-aware whitespace.
String text =
" Java ";
String result =
text.strip();- trim() is an older method.
- strip() uses Unicode-aware whitespace detection.
- For modern Java applications, strip() is often more appropriate.
stripLeading() and stripTrailing()
String text =
" Java ";
System.out.println(
text.stripLeading()
);
System.out.println(
text.stripTrailing()
);Searching in Strings
The String class provides methods for checking whether text exists and finding its position.
contains()
String message =
"Learn Java Programming";
System.out.println(
message.contains("Java")
);
System.out.println(
message.contains("Python")
);true
falseindexOf()
String text =
"Java Programming";
System.out.println(
text.indexOf('a')
);
System.out.println(
text.indexOf("Programming")
);The method returns the first matching index. If no match exists, it returns -1.
lastIndexOf()
String text =
"Java is a language";
System.out.println(
text.lastIndexOf('a')
);startsWith()
String url =
"https://programinds.com";
System.out.println(
url.startsWith("https://")
);endsWith()
String file =
"document.pdf";
System.out.println(
file.endsWith(".pdf")
);Extracting Substrings
A substring is a smaller section extracted from a larger String.
substring()
String text =
"Java Programming";
String first =
text.substring(5);
String second =
text.substring(
0,
4
);
System.out.println(first);
System.out.println(second);Programming
JavaSubstring Range Rules
substring(
beginIndex,
endIndex
)
BEGIN INDEX
INCLUDED
END INDEX
EXCLUDED
EXAMPLE
"JAVA"
substring(1, 3)
INDEX 1 INCLUDED
INDEX 3 EXCLUDED
RESULT
"AV"Concatenating Strings
Concatenation means combining multiple strings into one string.
The + Operator
String firstName = "Aarav";
String lastName = "Sharma";
String fullName =
firstName
+ " "
+ lastName;
System.out.println(fullName);Aarav SharmaSystem.out.println(
10 + 20
);
System.out.println(
"Total: " + 10 + 20
);
System.out.println(
"Total: " + (10 + 20)
);30
Total: 1020
Total: 30concat()
String first = "Hello";
String second = " Java";
String result =
first.concat(second);
System.out.println(result);Joining Strings
Joining is useful when multiple values must be combined with a delimiter such as a comma, hyphen, or space.
String.join()
String result =
String.join(
", ",
"Java",
"Python",
"JavaScript"
);
System.out.println(result);Java, Python, JavaScriptReplacing String Content
Replacement methods return new strings containing the requested changes.
replace()
String text =
"Java is easy";
String result =
text.replace(
"easy",
"powerful"
);
System.out.println(result);Java is powerfulreplaceFirst()
String text =
"Java Java Java";
String result =
text.replaceFirst(
"Java",
"Python"
);
System.out.println(result);Python Java JavareplaceAll()
The replaceAll() method replaces every substring matching a regular expression.
String text =
"Java123Programming456";
String result =
text.replaceAll(
"\\d",
""
);
System.out.println(result);JavaProgrammingSplitting Strings
Splitting divides one String into multiple smaller strings.
The split() Method
String languages =
"Java,Python,JavaScript";
String[] values =
languages.split(",");
for (String value : values) {
System.out.println(value);
}Java
Python
JavaScriptRegular Expressions in split()
The argument passed to split() is a regular expression, so special regex characters must be handled carefully.
String version =
"17.0.10";
String[] parts =
version.split("\\.");- The dot has special meaning in regular expressions.
- split(".") does not mean split by a literal dot.
- Use split("\\.") to split by an actual dot.
Repeating Strings
String line =
"-".repeat(20);
System.out.println(line);--------------------Matching Strings
String number = "12345";
boolean result =
number.matches("\\d+");
System.out.println(result);trueConverting Values to Strings
int age = 21;
double price = 499.99;
boolean active = true;
String ageText =
String.valueOf(age);
String priceText =
String.valueOf(price);
String activeText =
String.valueOf(active);String Formatting
String formatting creates readable text by inserting values into a predefined format.
String.format()
String name = "Aarav";
int age = 21;
String result =
String.format(
"Name: %s, Age: %d",
name,
age
);
System.out.println(result);formatted()
String result =
"Name: %s, Age: %d"
.formatted(
"Aarav",
21
);
System.out.println(result);Common Format Specifiers
%s
String
%d
Integer
%f
Floating-point number
%.2f
Floating-point number
with 2 decimal places
%b
Boolean
%c
Character
%n
Platform-specific new linedouble price = 499.9876;
String result =
String.format(
"Price: %.2f",
price
);
System.out.println(result);Price: 499.99Escape Sequences
\n
New line
\t
Tab
\"
Double quote
\'
Single quote
\\
Backslash
\r
Carriage return
\b
BackspaceSystem.out.println(
"Name:\tAarav\nLanguage:\tJava"
);Unicode Characters
String copyright =
"\u00A9";
System.out.println(copyright);Java strings use Unicode, allowing applications to represent text from many writing systems.
Text Blocks
Text blocks allow multiline strings to be written more clearly using triple double quotation marks.
String html = """
<html>
<body>
<h1>Hello Java</h1>
</body>
</html>
""";
System.out.println(html);Multiline Text
Write multiple lines without manually adding newline escape sequences.
HTML and JSON
Useful for embedded HTML, JSON, SQL, and other structured text.
Readability
Large text content becomes easier to read and maintain.
StringBuilder
StringBuilder is a mutable sequence of characters designed for efficient text modification.
StringBuilder builder =
new StringBuilder();
builder.append("Java");
builder.append(" ");
builder.append("Programming");
System.out.println(
builder.toString()
);Why Use StringBuilder?
STRING
""
│
▼
"Java"
│
▼
"Java Programming"
│
▼
"Java Programming Course"
MULTIPLE STRING RESULTS
STRINGBUILDER
ONE MUTABLE BUFFER
│
├── append
├── insert
├── replace
├── delete
└── reverse- Text is modified repeatedly.
- Text is built inside loops.
- Many values are appended dynamically.
- A mutable text buffer is required.
- Performance matters during repeated concatenation.
Creating StringBuilder
StringBuilder first =
new StringBuilder();
StringBuilder second =
new StringBuilder("Java");
StringBuilder third =
new StringBuilder(100);append()
StringBuilder builder =
new StringBuilder();
builder.append("Name: ");
builder.append("Aarav");
builder.append(", Age: ");
builder.append(21);
System.out.println(builder);insert()
StringBuilder builder =
new StringBuilder(
"Java Course"
);
builder.insert(
5,
"Programming "
);
System.out.println(builder);Java Programming Coursereplace() in StringBuilder
StringBuilder builder =
new StringBuilder(
"Java Course"
);
builder.replace(
5,
11,
"Programming"
);
System.out.println(builder);delete() and deleteCharAt()
StringBuilder builder =
new StringBuilder(
"Java Programming"
);
builder.delete(
4,
16
);
System.out.println(builder);StringBuilder builder =
new StringBuilder("Java");
builder.deleteCharAt(0);
System.out.println(builder);reverse()
StringBuilder builder =
new StringBuilder("Java");
builder.reverse();
System.out.println(builder);avaJStringBuilder Length and Capacity
StringBuilder builder =
new StringBuilder("Java");
System.out.println(
builder.length()
);
System.out.println(
builder.capacity()
);LENGTH
Number of characters
currently stored
CAPACITY
Amount of character storage
currently available
before internal expansionStringBuilder Method Chaining
String result =
new StringBuilder()
.append("Java")
.append(" ")
.append("Programming")
.append(" ")
.append("Course")
.toString();
System.out.println(result);StringBuffer
StringBuffer is a mutable character sequence similar to StringBuilder. Its methods are synchronized, making it suitable for certain shared multithreaded scenarios.
StringBuffer buffer =
new StringBuffer();
buffer.append("Java");
buffer.append(" Programming");
System.out.println(buffer);String vs StringBuilder vs StringBuffer
STRING
Immutable
Excellent for fixed text
Safe to share
Every modification produces
a new String result
STRINGBUILDER
Mutable
Fast for repeated modifications
Not synchronized
Preferred for normal
single-threaded text building
STRINGBUFFER
Mutable
Synchronized methods
Useful when the same mutable buffer
requires synchronization
Usually slower than StringBuilderString Performance
String result = "";
for (
int i = 1;
i <= 10000;
i++
) {
result =
result + i;
}Repeated concatenation can create many intermediate String objects because strings are immutable.
StringBuilder builder =
new StringBuilder();
for (
int i = 1;
i <= 10000;
i++
) {
builder.append(i);
}
String result =
builder.toString();String Concatenation in Loops
FEW SIMPLE CONCATENATIONS
Use +
REPEATED DYNAMIC CONCATENATION
Especially inside loops
Use StringBuilderCharacter Counting
String text =
"Java Programming";
char target = 'a';
int count = 0;
for (
int i = 0;
i < text.length();
i++
) {
if (
text.charAt(i) == target
) {
count++;
}
}
System.out.println(count);Word Counting
String sentence =
"Java is a powerful language";
String[] words =
sentence
.trim()
.split("\\s+");
System.out.println(
words.length
);Reversing a String
String text = "Java";
String reversed =
new StringBuilder(text)
.reverse()
.toString();
System.out.println(reversed);Palindrome Check
A palindrome reads the same forward and backward.
String text = "madam";
String reversed =
new StringBuilder(text)
.reverse()
.toString();
if (
text.equals(reversed)
) {
System.out.println(
"Palindrome"
);
} else {
System.out.println(
"Not a palindrome"
);
}Counting Vowels
String text =
"Java Programming"
.toLowerCase();
int count = 0;
for (
int i = 0;
i < text.length();
i++
) {
char character =
text.charAt(i);
if (
character == 'a'
|| character == 'e'
|| character == 'i'
|| character == 'o'
|| character == 'u'
) {
count++;
}
}
System.out.println(count);Removing Duplicate Characters
String text = "programming";
StringBuilder result =
new StringBuilder();
for (
int i = 0;
i < text.length();
i++
) {
char character =
text.charAt(i);
if (
result.indexOf(
String.valueOf(character)
) == -1
) {
result.append(character);
}
}
System.out.println(result);Anagram Check
Two strings are anagrams when they contain the same characters with the same frequencies in a different order.
import java.util.Arrays;
public class Main {
public static void main(
String[] args
) {
String first =
"listen"
.toLowerCase();
String second =
"silent"
.toLowerCase();
char[] firstArray =
first.toCharArray();
char[] secondArray =
second.toCharArray();
Arrays.sort(firstArray);
Arrays.sort(secondArray);
boolean result =
Arrays.equals(
firstArray,
secondArray
);
System.out.println(result);
}
}String Validation
String username = "Aarav";
if (
username == null
|| username.isBlank()
) {
System.out.println(
"Username is required"
);
} else {
System.out.println(
"Valid username"
);
}Email Validation Example
String email =
"user@example.com";
boolean valid =
email != null
&& !email.isBlank()
&& email.contains("@")
&& email.indexOf('@') > 0
&& email.lastIndexOf('.') >
email.indexOf('@');
System.out.println(valid);- This is a basic educational example.
- Real email validation can be more complex.
- Production applications should define validation according to actual business requirements.
Password Validation Example
String password =
"Java@123";
boolean hasMinimumLength =
password.length() >= 8;
boolean hasUppercase =
!password.equals(
password.toLowerCase()
);
boolean hasLowercase =
!password.equals(
password.toUpperCase()
);
boolean hasDigit =
password.matches(
".*\\d.*"
);
boolean valid =
hasMinimumLength
&& hasUppercase
&& hasLowercase
&& hasDigit;
System.out.println(valid);Common String Errors
STRING ERRORS
├── Using == for Content Comparison
├── Assuming equals() Checks Same Object
├── Forgetting Strings are Objects
├── Treating String as Primitive
├── Forgetting String Immutability
├── Calling Method Without Storing Result
├── Expecting toUpperCase() to Modify Original
├── Expecting replace() to Modify Original
├── Expecting trim() to Modify Original
├── Creating Unnecessary new String(...)
├── Relying on String Pool for Business Logic
├── Comparing References Instead of Content
├── Calling Method on null
├── Confusing null with Empty String
├── Confusing Empty with Blank
├── Calling isEmpty() on null
├── Calling isBlank() on null
├── Using text.equals(...) When text May Be null
├── Ignoring Case Requirements
├── Using Wrong Comparison Method
├── Invalid charAt() Index
├── Forgetting Index Starts at 0
├── Using length Instead of length()
├── Using length() for Arrays
├── Off-by-One Loop Errors
├── Using <= length()
├── Invalid substring Range
├── Forgetting End Index is Exclusive
├── Assuming substring Modifies Original
├── Forgetting indexOf() Returns -1
├── Using Returned -1 as Valid Index
├── Case-Sensitive contains() Mistakes
├── Case-Sensitive startsWith() Mistakes
├── Case-Sensitive endsWith() Mistakes
├── Incorrect Numeric Concatenation
├── Forgetting Parentheses Around Arithmetic
├── Repeated + Concatenation in Large Loops
├── Creating Too Many Intermediate Strings
├── Using StringBuilder for Simple Fixed Text
├── Using String When Heavy Mutation is Required
├── Forgetting toString() When Final String is Needed
├── Confusing StringBuilder with String
├── Expecting StringBuilder to Be Immutable
├── Sharing StringBuilder Unsafely Between Threads
├── Using StringBuffer Without Need
├── Ignoring Regular Expression Rules
├── Using split(".") for Literal Dot
├── Forgetting Regex Escaping
├── Using replaceAll() When Literal replace() is Enough
├── Incorrect Backslash Escaping
├── Incorrect Quote Escaping
├── Confusing char with String
├── Using Single Quotes for String
├── Using Double Quotes for char
├── Ignoring Unicode Whitespace
├── Assuming trim() and strip() are Identical
├── Incorrect Empty Input Word Count
├── Ignoring Leading and Trailing Spaces
├── Case-Sensitive Palindrome Checks
├── Ignoring Spaces in Phrase Palindromes
├── Incorrect Anagram Normalization
├── Ignoring Character Frequency
├── Weak Input Validation
├── Accepting Blank Required Values
├── Using Overly Simple Production Validation
├── Hardcoding Complex Messages with +
├── Ignoring String Formatting
├── Using Wrong Format Specifier
├── Forgetting String.format() Returns a String
├── Confusing formatted() with Mutation
├── Excessive intern() Usage
├── Assuming intern() is Always a Performance Improvement
└── Ignoring Readability in String ProcessingBest Practices
- Use string literals for normal String creation.
- Avoid unnecessary new String(...) calls.
- Use equals() for content comparison.
- Use equalsIgnoreCase() when case should not matter.
- Use == only for intentional reference comparison.
- Remember that strings are immutable.
- Store the result of methods that return modified strings.
- Check for null before calling instance methods when null is possible.
- Distinguish between null, empty, and blank values.
- Use isBlank() for required text validation when whitespace-only input is invalid.
- Use length() for strings.
- Use length for arrays.
- Respect zero-based indexing.
- Use length() - 1 for the final character index.
- Check indexOf() results before using them as indexes.
- Remember that substring end indexes are exclusive.
- Use contains() for simple substring checks.
- Use startsWith() for prefixes.
- Use endsWith() for suffixes.
- Use String.join() when combining values with a delimiter.
- Use replace() for literal replacement.
- Use replaceAll() only when regular expression behavior is needed.
- Remember that split() accepts a regular expression.
- Escape regular expression characters correctly.
- Use strip() for Unicode-aware surrounding whitespace removal.
- Use String.format() or formatted() for readable formatted output.
- Use appropriate format specifiers.
- Use text blocks for readable multiline text.
- Use StringBuilder for repeated text modification.
- Use StringBuilder inside large concatenation loops.
- Use + for small and simple concatenations.
- Avoid premature performance optimization for trivial string expressions.
- Use StringBuffer only when its synchronization characteristics are actually required.
- Normalize case before case-insensitive processing when appropriate.
- Normalize whitespace when business rules require it.
- Define validation rules clearly.
- Do not treat basic regex examples as complete production validation automatically.
- Keep string-processing code readable.
- Break complex transformations into clear steps.
- Use meaningful variable names such as normalizedEmail or trimmedName.
- Avoid excessive method chains when they reduce readability.
- Use constants for repeated fixed text.
- Consider locale requirements when changing case in international applications.
- Understand that Java String indexing is based on UTF-16 code units.
- Test empty input.
- Test blank input.
- Test null input when allowed.
- Test uppercase and lowercase input.
- Test special characters.
- Test Unicode text when relevant.
- Test boundary indexes.
- Test missing search values.
- Test repeated characters.
- Test very large text when performance matters.
String Method Reference
length()
Returns string length
charAt(index)
Returns character at index
equals(value)
Compares content
equalsIgnoreCase(value)
Compares content
without case sensitivity
compareTo(value)
Lexicographical comparison
compareToIgnoreCase(value)
Case-insensitive
lexicographical comparison
isEmpty()
Checks length == 0
isBlank()
Checks empty or whitespace-only
toUpperCase()
Returns uppercase version
toLowerCase()
Returns lowercase version
trim()
Removes limited leading
and trailing whitespace
strip()
Removes Unicode-aware
leading and trailing whitespace
stripLeading()
Removes leading whitespace
stripTrailing()
Removes trailing whitespace
contains(value)
Checks substring existence
indexOf(value)
Returns first matching index
lastIndexOf(value)
Returns last matching index
startsWith(value)
Checks prefix
endsWith(value)
Checks suffix
substring(start)
Extracts from start
to end of string
substring(start, end)
Extracts range
End is exclusive
concat(value)
Concatenates strings
replace(old, new)
Literal replacement
replaceFirst(regex, replacement)
Replaces first regex match
replaceAll(regex, replacement)
Replaces all regex matches
split(regex)
Splits into array
repeat(count)
Repeats string
matches(regex)
Checks full regex match
toCharArray()
Converts to char array
intern()
Returns pooled representation
formatted(values)
Formats current template
String.valueOf(value)
Converts value to String
String.format(format, values)
Creates formatted String
String.join(delimiter, values)
Joins multiple valuesCommon Misconceptions
- String is not a primitive type.
- String is a class.
- A String variable stores a reference.
- Strings are immutable.
- A String method does not normally modify the original object.
- Reassigning a String variable does not modify the old String object.
- The == operator does not perform general String content comparison.
- equals() compares String content.
- Two equal strings do not have to be the same object.
- Two references to the same pooled literal may point to one object.
- String Pool behavior should not replace equals() checks.
- new String("Java") is usually unnecessary.
- The String Pool exists because strings are safely reusable.
- length() is a method for String.
- length is a field for arrays.
- The first character index is 0.
- The last character index is length() - 1.
- charAt(length()) is invalid.
- An empty string is not null.
- A blank string is not necessarily empty.
- Whitespace-only text can be blank without being empty.
- Calling methods on null causes NullPointerException.
- contains() is case-sensitive.
- equals() is case-sensitive.
- equalsIgnoreCase() ignores letter case.
- compareTo() does not simply return -1, 0, or 1 in every case.
- indexOf() returns -1 when no match exists.
- substring() does not modify the original String.
- The substring end index is excluded.
- The + operator can perform arithmetic before string concatenation depending on expression order.
- split() uses regular expressions.
- A dot is a special regex character.
- replace() and replaceAll() are not identical.
- replaceAll() uses regular expressions.
- trim() and strip() are not exactly identical.
- StringBuilder is mutable.
- StringBuffer is mutable.
- StringBuilder and StringBuffer are not subclasses of String.
- StringBuilder is generally preferred for repeated single-threaded text building.
- StringBuffer synchronization does not make every surrounding workflow automatically thread-safe.
- StringBuilder is not necessary for every simple concatenation.
- Text blocks still create String objects.
- String.format() returns a new String.
- formatted() returns a new String.
- Java strings support Unicode.
- One char does not always represent one complete user-perceived Unicode character.
- Simple educational validation is not automatically production-grade validation.
Practice Exercises
- Create a String containing your full name.
- Print its length.
- Print the first character.
- Print the last character.
- Convert it to uppercase and lowercase.
- Create two equal string literals.
- Create another equal string using new String().
- Compare all references using ==.
- Compare all values using equals().
- Explain the results.
- Create a sentence.
- Check whether it contains Java.
- Find the first position of a selected character.
- Find the last position of that character.
- Check the sentence prefix and suffix.
- Store a full name containing first and last name.
- Find the space position.
- Extract the first name.
- Extract the last name.
- Display both values separately.
- Accept a sentence.
- Remove surrounding whitespace.
- Split by one or more whitespace characters.
- Count the resulting words.
- Handle empty input correctly.
- Accept a word.
- Normalize it to lowercase.
- Reverse it using StringBuilder.
- Compare original and reversed text.
- Display whether it is a palindrome.
- Accept a string.
- Accept a target character.
- Loop through the string.
- Count matching characters.
- Display the total count.
- Create text containing spaces.
- Remove leading and trailing whitespace.
- Remove every remaining normal space.
- Display the original and final values.
- Compare their lengths.
- Create a StringBuilder.
- Append a student name.
- Append age and marks.
- Add line breaks.
- Convert the final result to String.
- Display the report.
- Accept a paragraph.
- Count total characters.
- Count letters.
- Count digits.
- Count spaces.
- Count vowels.
- Count words.
- Display all results.
Common Interview Questions
What is a String in Java?
A String is an immutable object representing a sequence of characters and is an instance of the java.lang.String class.
Is String a primitive data type?
No. String is a class.
Why are strings immutable?
Immutability supports safe sharing, String Pool reuse, stable hashing, security, thread safety, and JVM optimizations.
What is the String Pool?
It is a JVM-managed area used to reuse canonical String objects, especially string literals.
What is the difference between == and equals() for strings?
The == operator compares reference identity, while equals() compares character content.
What is the difference between isEmpty() and isBlank()?
isEmpty() checks whether length is zero. isBlank() also returns true for strings containing only whitespace.
What does indexOf() return when no match exists?
It returns -1.
Is the substring end index included?
No. The begin index is included and the end index is excluded.
What is StringBuilder?
StringBuilder is a mutable character sequence used for efficient repeated text modification.
What is the difference between StringBuilder and StringBuffer?
Both are mutable, but StringBuffer methods are synchronized while StringBuilder is generally faster for normal single-threaded use.
When should StringBuilder be used?
It is useful when text is modified or concatenated repeatedly, especially inside loops.
What does intern() do?
It returns the canonical pooled representation of a String.
What is the difference between trim() and strip()?
strip() uses Unicode-aware whitespace detection, while trim() uses older limited whitespace rules.
Does replace() modify the original String?
No. Strings are immutable, so it returns a resulting String.
Why can repeated String concatenation be inefficient?
Because each modification may create intermediate immutable String objects.
Frequently Asked Questions
Can a String contain zero characters?
Yes. The empty string "" is a valid String object with length zero.
Is null the same as an empty string?
No. null means no String object is referenced, while an empty string is an existing String object with zero length.
Can String content be changed?
No. String objects are immutable. Operations that appear to modify text return new String values.
Why does "Java" == "Java" often return true?
Identical string literals are commonly reused from the String Pool, so both references may point to the same object.
Should I use == because literals may share objects?
No. Use equals() for content comparison because object identity is not the same as text equality.
Can StringBuilder be converted to String?
Yes. Call the toString() method.
Can String be converted to StringBuilder?
Yes. Pass the String to the StringBuilder constructor.
Should StringBuilder always replace the + operator?
No. The + operator is clear and appropriate for simple concatenations. StringBuilder is most useful for repeated dynamic modifications.
What should I learn after Strings?
The next lesson covers Classes in Java.
Key Takeaways
- A String represents a sequence of characters.
- String is a class, not a primitive type.
- The String class belongs to java.lang.
- String literals are written inside double quotation marks.
- Strings can also be created using new String().
- String literals are generally preferred.
- String objects are immutable.
- String methods do not modify the original String object.
- Modified text operations return String results.
- The String Pool reuses canonical string values.
- Identical literals can share one pooled object.
- The == operator compares references.
- The equals() method compares content.
- equalsIgnoreCase() compares content without case sensitivity.
- compareTo() performs lexicographical comparison.
- length() returns String length.
- String indexes begin at 0.
- The final valid index is length() - 1.
- charAt() accesses a character by index.
- toCharArray() creates a character array.
- isEmpty() checks zero length.
- isBlank() checks empty or whitespace-only text.
- null is different from empty.
- Empty is different from blank.
- toUpperCase() creates an uppercase result.
- toLowerCase() creates a lowercase result.
- trim() removes limited surrounding whitespace.
- strip() provides Unicode-aware whitespace removal.
- contains() checks substring existence.
- indexOf() finds the first match.
- lastIndexOf() finds the last match.
- A missing indexOf() match returns -1.
- startsWith() checks prefixes.
- endsWith() checks suffixes.
- substring() extracts part of a String.
- Substring begin indexes are included.
- Substring end indexes are excluded.
- The + operator concatenates strings.
- Expression order matters when combining strings and numbers.
- concat() combines strings.
- String.join() joins values using a delimiter.
- replace() performs literal replacement.
- replaceFirst() replaces the first regex match.
- replaceAll() replaces all regex matches.
- split() divides a String into an array.
- split() accepts a regular expression.
- repeat() repeats String content.
- matches() tests a regular expression against the complete String.
- String.valueOf() converts values to String.
- String.format() creates formatted text.
- formatted() formats a String template.
- Format specifiers represent different value types.
- Escape sequences represent special characters.
- Java strings support Unicode.
- Text blocks improve multiline text readability.
- StringBuilder is mutable.
- StringBuilder is useful for repeated modifications.
- append() adds content.
- insert() adds content at an index.
- replace() changes a range in StringBuilder.
- delete() removes a range.
- deleteCharAt() removes one character.
- reverse() reverses the character sequence.
- StringBuilder has length and capacity.
- StringBuilder supports method chaining.
- StringBuffer is also mutable.
- StringBuffer methods are synchronized.
- StringBuilder is generally preferred for normal single-threaded text building.
- Repeated String concatenation can create intermediate objects.
- StringBuilder is useful for large concatenation loops.
- Strings can be processed character by character.
- Strings can be reversed.
- Palindromes can be detected through comparison with reversed text.
- Character frequencies can be counted with loops.
- Words can be extracted using split().
- Anagrams require matching character frequencies.
- String validation should handle null, empty, and blank values intentionally.
- Production validation rules should match actual application requirements.
- Understanding Strings is essential for user input, files, databases, web applications, APIs, JSON, and enterprise Java development.
Summary
A String is an immutable object that represents a sequence of characters. String is one of the most frequently used classes in Java and is essential for processing names, messages, user input, files, URLs, JSON, database values, and application data.
Strings can be created using literals or the new keyword. String literals can be reused through the String Pool, while new String() explicitly creates a separate String object and is rarely necessary in normal application code.
String immutability means that an existing String object cannot be changed. Methods such as toUpperCase(), replace(), substring(), and strip() return String results instead of modifying the original object.
String comparison requires careful distinction between reference identity and content equality. The == operator compares references, while equals() compares the actual character content and should normally be used for String value comparison.
The String class provides methods for measuring length, accessing characters, comparing values, searching text, extracting substrings, replacing content, splitting values, changing case, removing whitespace, matching patterns, and formatting output.
StringBuilder provides a mutable character sequence for efficient repeated text modification. It is especially useful when building large strings dynamically or concatenating values repeatedly inside loops.
StringBuffer provides similar mutable operations with synchronized methods. StringBuilder is generally preferred for ordinary single-threaded text building, while StringBuffer may be considered when its synchronization behavior is specifically required.
Mastering Strings is essential because almost every Java application processes text. The concepts learned in this lesson will be used extensively in classes, objects, collections, exception handling, file handling, databases, web applications, APIs, Spring, and enterprise Java development.
- You understand what a String is.
- You understand why strings are important.
- You can create strings.
- You understand string literals.
- You understand new String().
- You know the difference between literals and new String().
- You understand that strings are objects.
- You understand the String class.
- You understand String immutability.
- You understand why strings are immutable.
- You understand the String Pool.
- You understand how pooled strings are reused.
- You understand heap and pooled String references.
- You understand intern().
- You understand String reference reassignment.
- You can find String length.
- You can access characters with charAt().
- You understand String indexing.
- You can loop through a String.
- You can convert a String to a character array.
- You can compare strings correctly.
- You understand the == operator.
- You can use equals().
- You can use equalsIgnoreCase().
- You understand compareTo().
- You understand compareToIgnoreCase().
- You can check empty strings.
- You can use isEmpty().
- You can use isBlank().
- You understand null, empty, and blank values.
- You can change String case.
- You can use toUpperCase().
- You can use toLowerCase().
- You can remove surrounding whitespace.
- You understand trim().
- You understand strip().
- You can use stripLeading() and stripTrailing().
- You can search inside strings.
- You can use contains().
- You can use indexOf().
- You can use lastIndexOf().
- You can use startsWith().
- You can use endsWith().
- You can extract substrings.
- You understand substring range rules.
- You can concatenate strings.
- You understand the + operator.
- You can use concat().
- You can join strings.
- You can use String.join().
- You can replace String content.
- You can use replace().
- You can use replaceFirst().
- You can use replaceAll().
- You can split strings.
- You understand regular expressions in split().
- You can repeat strings.
- You can match strings against patterns.
- You can convert values to strings.
- You can format strings.
- You can use String.format().
- You can use formatted().
- You understand common format specifiers.
- You understand escape sequences.
- You understand Unicode characters.
- You understand text blocks.
- You understand StringBuilder.
- You know why StringBuilder is useful.
- You can create StringBuilder objects.
- You can use append().
- You can use insert().
- You can replace StringBuilder content.
- You can delete StringBuilder content.
- You can reverse text.
- You understand StringBuilder length and capacity.
- You can chain StringBuilder methods.
- You understand StringBuffer.
- You know the difference between String, StringBuilder, and StringBuffer.
- You understand String performance considerations.
- You know when to avoid repeated String concatenation.
- You can count characters.
- You can count words.
- You can reverse strings.
- You can check palindromes.
- You can count vowels.
- You can remove duplicate characters.
- You can check anagrams.
- You can validate text values.
- You understand basic email validation.
- You understand password validation logic.
- You can identify common String errors.
- You know String best practices.
- You are ready to learn Classes in Java.