Java String Manipulation
Techniques
November 23, 2025
Java String Manipulation Techniques
Contents
1 Introduction 3
2 String Comparison Methods in Java 3
2.1 Content Equality with equals() and Case-Insensitive
Comparison with equalsIgnoreCase() . . . . . . . . . . 3
3 String Concatenation Techniques 5
3.1 Concatenation Using + Operator and concat() . . . . . . 5
4 Demonstrating String Immutability 6
4.1 Example Illustrating Immutability . . . . . . . . . . . . . . 6
5 Replacing Vowels with Asterisk 7
5.1 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 7
6 Extracting Substrings Using substring() 8
6.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
7 Searching for a Word in a Sentence 9
7.1 Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
8 Using StringBuffer for Mutable Strings 10
2
Java String Manipulation Techniques
8.1 Code Example . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9 Difference Between StringBuffer and StringBuilder 11
9.1 Demonstration . . . . . . . . . . . . . . . . . . . . . . . . . . 11
10 Using toString() Method in Classes 12
10.1 Sample Class and Usage . . . . . . . . . . . . . . . . . . . . 12
11 Tokenizing a Sentence Using StringTokenizer 13
11.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
12 Word Frequency in a Paragraph 14
12.1 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 14
13 Cleaning and Formatting Strings 16
13.1 Code Sample . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
14 Finding Common Substrings Using a Loop 17
14.1 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . 17
15 Demonstrating Mutability with String and StringBuffer 19
15.1 Complete Code . . . . . . . . . . . . . . . . . . . . . . . . . . 19
16 Uppercase Conversion and Palindrome Check 20
3
Java String Manipulation Techniques
16.1 Code with Explanation and Output . . . . . . . . . . . . . 20
4
Java String Manipulation Techniques
1 Introduction
Java strings are fundamental data types used extensively for text
processing. Understanding how to manipulate strings efficiently is
crucial for any Java programmer. This document systematically ex-
plores a series of Java string operations, ranging from basic compar-
isons and concatenations to advanced topics such as immutability,
mutability, tokenization, substring search, and palindrome checking.
Each section presents a clear explanation, accompanied by sample
code and expected outputs, to provide a comprehensive understand-
ing of these concepts.
2 String Comparison Methods in Java
Comparing strings accurately is a common requirement. Java
provides several methods with different behaviors concerning con-
tent equality and case sensitivity.
2.1 Content Equality with equals() and Case-Insensitive
Comparison with equalsIgnoreCase()
The equals() method compares two strings exactly, including
case. The equalsIgnoreCase() method ignores case differences.
// Example of string comparison
5
Java String Manipulation Techniques
import [Link];
public class StringComparison {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](”Enter first string: ”);
String s1 = [Link]();
[Link](”Enter second string: ”);
String s2 = [Link]();
if ([Link](s2)) {
[Link](”Strings are exactly equal.”);
} else if ([Link](s2)) {
[Link](”Strings are equal ignoring case.”);
} else {
[Link](”Strings are different.”);
}
[Link]();
}
}
Output example:
Enter first string: Hello
Enter second string: hello
Strings are equal ignoring case.
6
Java String Manipulation Techniques
3 String Concatenation Techniques
Java offers multiple ways to concatenate strings, with the most
common being the + operator and the concat() method.
3.1 Concatenation Using + Operator and concat()
// Concatenation example
public class StringConcat {
public static void main(String[] args) {
String s1 = ”Java”;
String s2 = ”Programming”;
String result1 = s1 + ” ” + s2;
String result2 = [Link](” ”).concat(s2);
[Link](”Using + operator: ” + result1);
[Link](”Using concat(): ” + result2);
}
}
Output:
Using + operator: Java Programming
Using concat(): Java Programming
7
Java String Manipulation Techniques
4 Demonstrating String Immutability
Strings in Java are immutable, meaning any modification results
in a new string object.
4.1 Example Illustrating Immutability
// Demonstrate string immutability
public class StringImmutability {
public static void main(String[] args) {
String original = ”Immutable”;
String modified = [Link](’I’, ’i’);
[Link](”Original string: ” + original);
[Link](”Modified string: ” + modified);
}
}
Explanation: The replace() method does not change the orig-
inal string but returns a new modified string.
Output:
Original string: Immutable
Modified string: immutable
8
Java String Manipulation Techniques
5 Replacing Vowels with Asterisk
This program replaces all vowels in a string with * using Java
String methods and regular expressions.
5.1 Implementation
// Replace vowels with ’*’
import [Link];
public class ReplaceVowels {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](”Enter a string: ”);
String input = [Link]();
String replaced = [Link](”(?i)[aeiou]”, ”*”);
[Link](”After replacement: ” + replaced);
[Link]();
}
}
Output example:
Enter a string: Education
After replacement: *d*c*t**n
9
Java String Manipulation Techniques
6 Extracting Substrings Using substring()
Java’s substring() method extracts parts of a string by specify-
ing start and end indices.
6.1 Example
// Substring extraction
public class SubstringExample {
public static void main(String[] args) {
String text = ”JavaProgramming”;
String sub1 = [Link](0, 4); // ”Java”
String sub2 = [Link](4); // ”Programming”
[Link](”First part: ” + sub1);
[Link](”Second part: ” + sub2);
}
}
Output:
First part: Java
Second part: Programming
10
Java String Manipulation Techniques
7 Searching for a Word in a Sentence
Using indexOf() and contains(), you can locate a word within
a sentence.
7.1 Program
// Search word position
import [Link];
public class WordSearch {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](”Enter a sentence: ”);
String sentence = [Link]();
[Link](”Enter word to search: ”);
String word = [Link]();
if ([Link](word)) {
int position = [Link](word);
[Link](”Word found at position: ” + position)
} else {
[Link](”Word not found.”);
}
[Link]();
}
}
11
Java String Manipulation Techniques
Output example:
Enter a sentence: The quick brown fox
Enter word to search: brown
Word found at position: 10
8 Using StringBuffer for Mutable Strings
StringBuffer allows modification after creation, supporting op-
erations such as append, insert, and reverse.
8.1 Code Example
// StringBuffer operations
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer(”Hello”);
[Link](” World”);
[Link](6, ”Java ”);
[Link]();
[Link](”Modified string: ” + [Link]());
}
}
Output:
12
Java String Manipulation Techniques
Modified string: dlroW avaJ olleH
9 Difference Between StringBuffer and StringBuilder
Both classes provide mutable strings, but StringBuffer is syn-
chronized (thread-safe), while StringBuilder is not, making the lat-
ter faster in single-thread scenarios.
9.1 Demonstration
// Compare StringBuffer and StringBuilder
public class BufferBuilderDifference {
public static void main(String[] args) {
StringBuffer sbuf = new StringBuffer(”Buffer”);
StringBuilder sbld = new StringBuilder(”Builder”);
[Link](” Class”);
[Link](” Class”);
[Link](”StringBuffer: ” + sbuf);
[Link](”StringBuilder: ” + sbld);
}
}
Output:
13
Java String Manipulation Techniques
StringBuffer: Buffer Class
StringBuilder: Builder Class
10 Using toString() Method in Classes
Overriding toString() in a class allows convenient string rep-
resentation of object data.
10.1 Sample Class and Usage
// toString() example
class Person {
String name;
int age;
Person(String n, int a) {
name = n;
age = a;
}
@Override
public String toString() {
return ”Person[name=” + name + ”, age=” + age + ”]”;
}
}
14
Java String Manipulation Techniques
public class ToStringDemo {
public static void main(String[] args) {
Person p = new Person(”Alice”, 30);
[Link]([Link]());
}
}
Output:
Person[name=Alice, age=30]
11 Tokenizing a Sentence Using StringTokenizer
The StringTokenizer class can split a sentence into tokens (words)
and count them.
11.1 Example
// Tokenize and count words
import [Link];
import [Link];
public class TokenCount {
public static void main(String[] args) {
15
Java String Manipulation Techniques
Scanner sc = new Scanner([Link]);
[Link](”Enter a sentence: ”);
String sentence = [Link]();
StringTokenizer tokenizer = new StringTokenizer(sentence);
int count = [Link]();
[Link](”Number of words: ” + count);
[Link]();
}
}
Output example:
Enter a sentence: Java programming language
Number of words: 3
12 Word Frequency in a Paragraph
This program counts occurrences of a specific word in a para-
graph using string methods.
12.1 Implementation
// Word frequency count
import [Link];
16
Java String Manipulation Techniques
public class WordFrequency {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](”Enter a paragraph:”);
String paragraph = [Link]();
[Link](”Enter word to count: ”);
String word = [Link]();
String lowerPara = [Link]();
String lowerWord = [Link]();
int frequency = 0;
int index = 0;
while ((index = [Link](lowerWord, index)) != -1) {
frequency++;
index += [Link]();
}
[Link](”Frequency of \”” + word + ”\”: ” + freque
[Link]();
}
}
Output example:
Enter a paragraph:
17
Java String Manipulation Techniques
Java is a popular programming language. Java is platform-independent.
Enter word to count: Java
Frequency of ”Java”: 2
13 Cleaning and Formatting Strings
Using replace() and toLowerCase() methods, user inputs can
be cleaned and normalized.
13.1 Code Sample
// Clean and format string
import [Link];
public class CleanFormat {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](”Enter input string: ”);
String input = [Link]();
String cleaned = [Link](”,”, ””).replace(”.”, ””).toLo
[Link](”Cleaned string: ” + cleaned);
[Link]();
}
}
18
Java String Manipulation Techniques
Output example:
Enter input string: Hello, World.
Cleaned string: hello world
14 Finding Common Substrings Using a Loop
This program compares two strings and displays all common sub-
strings.
14.1 Implementation
// Find common substrings
import [Link];
import [Link];
public class CommonSubstrings {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](”Enter first string: ”);
String s1 = [Link]();
[Link](”Enter second string: ”);
String s2 = [Link]();
HashSet<String> common = new HashSet<>();
19
Java String Manipulation Techniques
for (int len = 1; len <= [Link]([Link](), [Link]());
for (int i = 0; i <= [Link]() - len; i++) {
String substr = [Link](i, i + len);
if ([Link](substr)) {
[Link](substr);
}
}
}
[Link](”Common substrings:”);
for (String str : common) {
[Link](str);
}
[Link]();
}
}
Explanation: The program finds all substrings of all lengths present
in both strings, displaying unique matches.
20
Java String Manipulation Techniques
15 Demonstrating Mutability with String and
StringBuffer
A class example shows real-time mutability differences between
String (immutable) and StringBuffer (mutable).
15.1 Complete Code
// Mutability demonstration
public class MutabilityDemo {
String immutableString = ”Hello”;
StringBuffer mutableString = new StringBuffer(”Hello”);
public void modify() {
[Link](” World”); // Does not change immutab
[Link](” World”); // Modifies mutableString
}
public void display() {
[Link](”Immutable String: ” + immutableString);
[Link](”Mutable StringBuffer: ” + mutableString);
}
public static void main(String[] args) {
MutabilityDemo demo = new MutabilityDemo();
[Link]();
21
Java String Manipulation Techniques
[Link]();
}
}
Output:
Immutable String: Hello
Mutable StringBuffer: Hello World
16 Uppercase Conversion and Palindrome Check
This Java application reads a string, converts it to uppercase, and
checks if it is a palindrome using string methods.
16.1 Code with Explanation and Output
// Palindrome checking program
import [Link];
public class PalindromeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link](”Enter a string: ”);
String input = [Link]();
22
Java String Manipulation Techniques
// Convert to uppercase for uniform comparison
String upperInput = [Link]();
// Remove non-alphanumeric characters for accurate palindrome
String cleaned = [Link](”[^A-Z0-9]”, ””);
// Reverse the cleaned string
String reversed = new StringBuilder(cleaned).reverse().toStri
[Link](”Uppercase input: ” + upperInput);
if ([Link](reversed)) {
[Link](”The string is a palindrome.”);
} else {
[Link](”The string is not a palindrome.”);
}
[Link]();
}
}
Explanation: Converting the input to uppercase normalizes case
differences. Cleaning removes spaces and punctuation for a proper
palindrome check. The reversed string is compared to the cleaned
original to determine palindrome status.
Output example:
Enter a string: Madam, in Eden, I’m Adam
23
Java String Manipulation Techniques
Uppercase input: MADAM, IN EDEN, I’M ADAM
The string is a palindrome.
24
Java String Manipulation Techniques
References
• Oracle Java Documentation: [Link]
8/docs/api/java/lang/[Link]
• GeeksforGeeks Java String Tutorials: [Link]
org/java-string-methods/
• Oracle StringBuffer API: [Link]
8/docs/api/java/lang/[Link]
• Oracle StringTokenizer API: [Link]
8/docs/api/java/util/[Link]
25