0% found this document useful (0 votes)
7 views25 pages

Java String Manipulation Techniques

Uploaded by

10 HEADED GAMING
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views25 pages

Java String Manipulation Techniques

Uploaded by

10 HEADED GAMING
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

Common questions

Powered by AI

Java provides the StringTokenizer class to tokenize sentences into individual words. It splits a sentence based on spaces and counts each token. For example, using StringTokenizer on "Java programming language" results in three tokens: "Java", "programming", and "language" .

StringBuffer and StringBuilder both allow for mutable strings in Java, but StringBuffer is synchronized, making it thread-safe and suitable for use in multi-threaded environments. However, this synchronization incurs some performance overhead. In contrast, StringBuilder is not synchronized, which makes it faster than StringBuffer in single-threaded applications where thread safety isn't a concern .

Overriding the toString() method in Java objects provides a way to give a meaningful string representation of an object's data, which is useful for debugging and logging. For example, a Person class can override toString() to return formatted string showing name and age: Person[name=Alice, age=30].

The StringBuffer class in Java supports mutability, allowing modifications to be made without creating new objects. Unlike immutable String objects, a StringBuffer can be altered directly using methods like append() and insert(). For instance, appending " World" to a StringBuffer initialized with "Hello" results in "Hello World", while altering a String object would require creating a new string .

A palindrome check in Java involves converting the string to uppercase for uniformity, removing non-alphanumeric characters using regular expressions, and then comparing the original cleaned string to its reversed version. For example, the input "Madam, in Eden, I’m Adam" is normalized to "MADAMINEDENIMADAM" and checked for palindrome properties .

To count the frequency of a specific word in a paragraph using Java, one can convert both the paragraph and the search word to lowercase to ensure case-insensitive comparison. The indexOf() method is used iteratively to find occurrences of the word. For example, in the paragraph "Java is a popular programming language. Java is platform-independent.", the word "Java" appears twice .

Java strings are immutable, which means their values cannot be changed once created. When using methods like replace(), a new string is returned with the modifications, leaving the original string unchanged. For example, calling 'Immutable'.replace('I', 'i') produces a new string "immutable" while the original remains "Immutable" .

Java's substring() method can be used to extract parts of a string by specifying the start index, and optionally the end index. For example, in the string "JavaProgramming", calling substring(0, 4) extracts "Java", and substring(4) extracts "Programming" .

Java uses the equals() method for case-sensitive string comparison, which checks if two strings are exactly the same, including the case of the characters. For case-insensitive checks, Java provides the equalsIgnoreCase() method, which compares two strings for equality, ignoring the case of the characters .

Java utilizes regular expressions to perform complex string manipulations, such as replacing all vowels with an asterisk (*). An example implementation uses the replaceAll() method with the regex pattern (?i)[aeiou] to replace vowels in a string. For instance, in the string "Education", vowels are replaced to form "*d*c*t**n" .

You might also like