0% found this document useful (0 votes)
4 views68 pages

Module 2-2

Strings in Java are immutable, meaning once created, their contents cannot be changed, and any modification results in a new String object. This immutability supports optimizations like String Pool, enhances security, ensures thread safety, and maintains consistent hashing in collections. In contrast, StringBuffer and StringBuilder are mutable, allowing modifications without creating new objects, with StringBuffer being synchronized for thread safety and StringBuilder offering better performance.
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)
4 views68 pages

Module 2-2

Strings in Java are immutable, meaning once created, their contents cannot be changed, and any modification results in a new String object. This immutability supports optimizations like String Pool, enhances security, ensures thread safety, and maintains consistent hashing in collections. In contrast, StringBuffer and StringBuilder are mutable, allowing modifications without creating new objects, with StringBuffer being synchronized for thread safety and StringBuilder offering better performance.
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

Why Strings are Immutable in Java?

Justify with Examples.


Definition
A String is an immutable object in Java. Once a String object is created, its contents cannot be
changed. Any modification operation creates a new String object instead of modifying the
existing object.

Example 1: Demonstrating Immutability


class ImmutableDemo {
public static void main(String args[]) {

String s1 = "Java";

[Link](" Programming");

[Link](s1);
}
}

Output
Java

Explanation

The statement

[Link](" Programming");

creates a new String object "Java Programming".

However, since it is not assigned back to s1, the original object "Java" remains unchanged.

Hence the output is:

Java

This proves that String objects cannot be modified.


Example 2: Creating a New Object
class ImmutableDemo2 {
public static void main(String args[]) {

String s1 = "Java";

s1 = [Link](" Programming");

[Link](s1);
}
}

Output
Java Programming

Explanation

Here a new String object is created and its reference is assigned back to s1.

The original String object is still not modified.

Reasons Why Strings are Immutable


1. String Pool Optimization

String literals are stored in the String Constant Pool.

Example:

String s1 = "Java";
String s2 = "Java";

Both references point to the same object.

"Java"
/ \
s1 s2

If strings were mutable, changing through one reference would affect all references.
Immutability avoids this problem.

2. Security

Strings are used to store:

String password = "admin123";


String url = "jdbc:mysql://localhost";
String path = "/system/config";

Immutability prevents unauthorized modification of these critical values.

3. Thread Safety

Example:

String msg = "Welcome";

Multiple threads can safely access the same String object because its contents cannot change.

No synchronization is required.

4. HashMap Support

Strings are commonly used as keys.

HashMap<String,Integer> map = new HashMap<>();

[Link]("Java",100);

If String contents could change, the hash code would also change, causing retrieval failures.

Immutability ensures consistent hashing.

Mutable Alternatives
StringBuffer
StringBuffer sb = new StringBuffer("Java");
[Link](" Programming");

[Link](sb);

Output:

Java Programming

StringBuilder
StringBuilder sb = new StringBuilder("Java");
[Link](" Programming");

[Link](sb);

Output:

Java Programming

Conclusion
Strings are immutable in Java to support String Pool optimization, improve security, ensure
thread safety, and provide reliable hashing behavior. Any modification operation results in the
creation of a new String object rather than altering the existing one.

Why StringBuffer is Mutable? Justify with Examples.


Definition

StringBuffer is a predefined class in the [Link] package that represents a modifiable


(mutable) sequence of characters. Unlike String objects, the contents of a StringBuffer object
can be changed after creation.

Why StringBuffer is Mutable?


StringBuffer allows modification of its contents without creating a new object.

Operations such as:

●​ append()
●​ insert()
●​ replace()
●​ reverse()

directly modify the existing object.

StringBuffer internally uses a dynamic character buffer which can grow automatically whenever
additional space is required.

Example 1: append()
class AppendDemo {

public static void main(String args[]) {

StringBuffer sb =

new StringBuffer("Java");

[Link](" Programming");

[Link](sb);

Output

Java Programming

Explanation
The append() method modifies the existing StringBuffer object by adding new characters at
the end.

Example 2: insert()
class InsertDemo {

public static void main(String args[]) {

StringBuffer sb =

new StringBuffer("I Java");

[Link](2,"like ");

[Link](sb);

Output

I like Java

Explanation

The insert() method inserts characters into the existing object without creating a new object.

Example 3: reverse()
class ReverseDemo {

public static void main(String args[]) {


StringBuffer sb =

new StringBuffer("abcdef");

[Link]();

[Link](sb);

Output

fedcba

Explanation

The reverse() method directly modifies the character sequence present in the StringBuffer
object.

Advantages of Mutability
1.​ Faster than String for repeated modifications.
2.​ Reduces creation of unnecessary objects.
3.​ Better memory utilization.
4.​ Supports dynamic growth using internal buffer capacity.
5.​ Thread-safe and synchronized.

Conclusion
StringBuffer is mutable because it allows direct modification of its character sequence through
methods such as append(), insert(), replace(), and reverse(). Unlike String objects,
no new object is created during modification, making StringBuffer efficient for frequent string
operations.

Differentiate Between String, StringBuffer


and StringBuilder Classes
Introduction
String, StringBuffer and StringBuilder are predefined classes available in the [Link]
package used for handling character sequences in Java. String objects are immutable, whereas
StringBuffer and StringBuilder objects are mutable. StringBuffer is synchronized and
thread-safe, while StringBuilder is unsynchronized and provides better performance.

String Class
●​ String is a predefined final class present in [Link] package.
●​ String objects are immutable in nature.
●​ Once created, the contents of a String object cannot be modified.
●​ Any modification results in the creation of a new object.

Example

String s = "Java";

s = s + " Programming";
[Link](s);

Output

Java Programming

StringBuffer Class
●​ StringBuffer is a mutable class.
●​ It allows modification of character sequences without creating new objects.
●​ It is synchronized and thread-safe.
●​ Suitable for multi-threaded applications.

Example

StringBuffer sb = new StringBuffer("Java");

[Link](" Programming");

[Link](sb);

Output

Java Programming

StringBuilder Class
●​ StringBuilder was introduced in JDK 1.5.
●​ It is mutable like StringBuffer.
●​ It is not synchronized and hence not thread-safe.
●​ It provides better performance than StringBuffer.

Example

StringBuilder sb = new StringBuilder("Java");

[Link](" Programming");

[Link](sb);
Output

Java Programming

Difference Between String, StringBuffer and StringBuilder

String StringBuffer StringBuilder

Introduced in JDK 1.0 Introduced in JDK 1.0 Introduced in JDK 1.5

Immutable in nature Mutable in nature Mutable in nature

Thread-safe because Thread-safe because Not thread-safe


immutable synchronized

New object is created Existing object is modified Existing object is modified


whenever modification occurs

Slower for frequent Faster than String Faster than StringBuffer


modifications

Objects can be created with Objects can be created Objects can be created
or without new keyword only using new keyword only using new keyword

Supports String Constant Does not use String Does not use String
Pool Constant Pool Constant Pool
+ operator can be used for Uses methods such as Uses methods such as
concatenation append() append()

Suitable for fixed data Suitable for multi-threaded Suitable for


applications single-threaded
applications

Memory efficient for read-only Less efficient due to More efficient and
strings synchronization overhead high-performance

Program Demonstrating String, StringBuffer and


StringBuilder
class Demo {

public static void main(String args[]) {

String s = "Java";

s = s + " Programming";

StringBuffer sb1 = new StringBuffer("Java");

[Link](" Programming");

StringBuilder sb2 = new StringBuilder("Java");

[Link](" Programming");

[Link]("String : " + s);


[Link]("StringBuffer: " + sb1);

[Link]("StringBuilder: " + sb2);

Output

String : Java Programming

StringBuffer : Java Programming

StringBuilder: Java Programming

Conclusion
String, StringBuffer and StringBuilder are widely used classes for string manipulation in Java.
String is immutable and suitable for constant data, StringBuffer is mutable and thread-safe,
whereas StringBuilder is mutable and provides better performance for single-threaded
applications. Therefore, the choice of class depends on the application’s requirements regarding
mutability, thread safety and performance.

Explain How Strings are Compared in


Sorting Algorithms. Give Example.
Introduction
In Java, strings are compared using the compareTo() method of the String class. The
compareTo() method is defined in the Comparable interface implemented by the String
class. It compares two strings lexicographically (dictionary order) based on the Unicode values
of their characters. Sorting algorithms use this method to determine the order of strings and
arrange them alphabetically.
compareTo() Method
Syntax

int compareTo(String str)

Return Values

Return Value Meaning

0 Both strings are equal

Positive Value Invoking string is greater

Negative Value Invoking string is smaller

Example

String s1 = "chutiya";

String s2 = "anish";

[Link]([Link](s2));

Output:

Positive Value

Because:

'c' > 'a'

Therefore "chutiya" comes after "anish" alphabetically.


Program to Sort Strings Using compareTo()
import [Link];

class Main {

public static void main(String[] args) {

String arr[] = {

"chutiya",

"anish",

"dhurandhar",

"bruno"

};

[Link]("Before Sorting:");

[Link]([Link](arr));

for(int i = 0; i < [Link]; i++) {

for(int j = i + 1; j < [Link]; j++) {

if(arr[i].compareTo(arr[j]) > 0) {

String t = arr[i];

arr[i] = arr[j];
arr[j] = t;

[Link]("After Sorting:");

[Link]([Link](arr));

Output
Before Sorting:

[chutiya, anish, dhurandhar, bruno]

After Sorting:

[anish, bruno, chutiya, dhurandhar]

Working of the Program


Initial array:

[chutiya, anish, dhurandhar, bruno]

Step 1

"chutiya".compareTo("anish")

returns a positive value because:


c>a

Hence the strings are swapped.

[anish, chutiya, dhurandhar, bruno]

Step 2

"chutiya".compareTo("bruno")

returns a positive value because:

c>b

Hence swap occurs.

[anish, bruno, dhurandhar, chutiya]

Step 3

"dhurandhar".compareTo("chutiya")

returns a positive value because:

d>c

Hence swap occurs.

[anish, bruno, chutiya, dhurandhar]

Thus the strings are arranged in alphabetical order.

Algorithm
1.​ Read all strings into an array.
2.​ Compare two strings using compareTo().
3.​ If compareTo() returns a positive value, swap the strings.
4.​ Repeat the process for all elements.
5.​ Display the sorted array.
Advantages of compareTo()
1.​ Provides lexicographical comparison of strings.
2.​ Useful for sorting and searching operations.
3.​ Returns positive, negative or zero values for easy comparison.
4.​ Implemented through the Comparable interface.
5.​ Widely used in sorting algorithms and collections.

Conclusion
Strings are compared in sorting algorithms using the compareTo() method. The method
compares strings character by character based on Unicode values and returns a positive,
negative or zero value. Sorting algorithms use these return values to arrange strings in
lexicographical (alphabetical) order efficiently.

Illustrate the Different Type Signatures of


String Searching Methods with Examples.
Introduction
Java provides searching methods in the String class to locate characters and substrings within a
string. The two important searching methods are:

1.​ indexOf()
2.​ lastIndexOf()

These methods return the position of a character or substring if found; otherwise they return -1.

1. indexOf() Method
The indexOf() method searches for the first occurrence of a character or substring.

Type Signatures
int indexOf(int ch)
int indexOf(int ch, int startIndex)
int indexOf(String str)
int indexOf(String str, int startIndex)

Example
class IndexDemo {
public static void main(String args[]) {

String s = "Java Programming";

[Link](
[Link]('a'));

[Link](
[Link]('a',2));

[Link](
[Link]("Program"));

[Link](
[Link]("gram",5));
}
}

Output
1
3
5
8

2. lastIndexOf() Method
The lastIndexOf() method searches for the last occurrence of a character or substring.

Type Signatures
int lastIndexOf(int ch)
int lastIndexOf(int ch, int startIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int startIndex)

Example
class LastIndexDemo {
public static void main(String args[]) {

String s = "Java Java Java";

[Link](
[Link]('a'));

[Link](
[Link]('a',5));

[Link](
[Link]("Java"));

[Link](
[Link]("Java",8));
}
}

Output
13
8
10
5

Comprehensive Example
class SearchDemo {
public static void main(String args[]) {

String s =
"Now is the time for all good men "
+ "to come to the aid of their country.";

[Link](
"indexOf(t) = "
+ [Link]('t'));

[Link](
"lastIndexOf(t) = "
+ [Link]('t'));

[Link](
"indexOf(the) = "
+ [Link]("the"));

[Link](
"lastIndexOf(the) = "
+ [Link]("the"));
}
}

Summary Table
Method Purpose

indexOf(int ch) First occurrence of character

indexOf(String str) First occurrence of substring

indexOf(ch,startIndex) First occurrence after specified index

indexOf(str,startIndex) First substring occurrence after specified index

lastIndexOf(int ch) Last occurrence of character


lastIndexOf(String str) Last occurrence of substring

lastIndexOf(ch,startIndex) Search backward from specified index

lastIndexOf(str,startIndex Last substring occurrence before specified index


)

Illustrate the Various Constructors of


String and StringBuffer Classes with
Examples.
Introduction
Constructors are special methods used to initialize objects. The String class provides several
constructors for creating string objects from character arrays, byte arrays, other String objects,
StringBuffer objects and StringBuilder objects. Similarly, StringBuffer provides constructors for
creating mutable strings with different capacities and initial values.

A) Constructors of String Class


1. Default Constructor
String s = new String();

Creates an empty String.

Example
String s = new String();
[Link](s);

2. Character Array Constructor


String(char chars[])

Example
char ch[] =
{'J','a','v','a'};

String s =
new String(ch);

[Link](s);

Output:

Java

3. Character Array Subset Constructor


String(char chars[],
int startIndex,
int numChars)

Example
char ch[] =
{'a','b','c','d','e','f'};

String s =
new String(ch,2,3);

[Link](s);

Output:

cde

4. String Object Constructor


String(String strObj)
Example
String s1 = "Java";

String s2 =
new String(s1);

[Link](s2);

Output:

Java

5. Byte Array Constructor


String(byte ascii[])

Example
byte b[] =
{65,66,67,68};

String s =
new String(b);

[Link](s);

Output:

ABCD

6. Byte Array Subset Constructor


String(byte ascii[],
int startIndex,
int numChars)

Example
byte b[] =
{65,66,67,68,69,70};

String s =
new String(b,2,3);
[Link](s);

Output:

CDE

7. StringBuffer Constructor
String(StringBuffer strBufObj)

Example
StringBuffer sb =
new StringBuffer("Java");

String s =
new String(sb);

[Link](s);

Output:

Java

8. StringBuilder Constructor
String(StringBuilder strBuildObj)

Example
StringBuilder sb =
new StringBuilder("Java");

String s =
new String(sb);

[Link](s);

Output:

Java
B) Constructors of StringBuffer Class
1. Default Constructor
StringBuffer()

Example
StringBuffer sb =
new StringBuffer();

[Link](
[Link]());

Output:

16

2. Capacity Constructor
StringBuffer(int size)

Example
StringBuffer sb =
new StringBuffer(50);

[Link](
[Link]());

Output:

50

3. String Constructor
StringBuffer(String str)

Example
StringBuffer sb =
new StringBuffer("Java");
[Link](sb);

Output:

Java

4. CharSequence Constructor
StringBuffer(CharSequence chars)

Example
CharSequence cs =
"Programming";

StringBuffer sb =
new StringBuffer(cs);

[Link](sb);

Output:

Programming

List and Explain Various String Modifying


Methods with Examples.
Introduction
String objects in Java are immutable. Therefore, whenever a string modification operation is
performed, a new String object is created and returned. The String class provides several
methods for modifying strings such as substring(), concat(), replace(), and trim().

1. substring()
The substring() method is used to extract a portion of a string.

Syntax
String substring(int startIndex)
String substring(int startIndex,
int endIndex)

Example
class SubstringDemo {
public static void main(String args[]) {

String s = "Programming";

[Link](
[Link](3));

[Link](
[Link](3,7));
}
}

Output
gramming
gram

2. concat()
The concat() method is used to join two strings.
Syntax
String concat(String str)

Example
class ConcatDemo {
public static void main(String args[]) {

String s1 = "Java";

String s2 =
[Link](" Programming");

[Link](s2);
}
}

Output
Java Programming

3. replace()
The replace() method replaces characters or character sequences.

Syntax
String replace(char original,
char replacement)
String replace(CharSequence original,
CharSequence replacement)

Example 1
class ReplaceDemo1 {
public static void main(String args[]) {

String s = "Hello";

[Link](
[Link]('l','w'));
}
}
Output
Hewwo

Example 2
class ReplaceDemo2 {
public static void main(String args[]) {

String s =
"Java Programming";

[Link](
[Link](
"Java",
"Python"));
}
}

Output
Python Programming

4. trim()
The trim() method removes leading and trailing white spaces from a string.

Syntax
String trim()

Example
class TrimDemo {
public static void main(String args[]) {

String s =
" Hello World ";

[Link](
[Link]());
}
}
Output
Hello World

Summary Table
Method Purpose

substring() Extracts part of a string

concat() Concatenates two strings

replace() Replaces characters or substrings

trim() Removes leading and trailing spaces

Conclusion
The String class provides several modifying methods such as substring(), concat(),
replace(), and trim(). Since String objects are immutable, these methods do not modify the
original string; instead, they return a new String object containing the modified result. These
methods are widely used in Java string processing applications.

Explain How Substring is Extracted with


String Class. Give Examples.
Introduction
A substring is a sequence of characters that forms a part of another string. Java provides the
substring() method in the String class to extract portions of a string. Since String objects are
immutable, the substring() method returns a new String object containing the extracted
characters.

Forms of substring() Method


1. substring(int startIndex)

Extracts characters from the specified starting index up to the end of the string.

Syntax
String substring(int startIndex)

Example
class SubStringDemo1 {
public static void main(String args[]) {

String s = "Programming";

[Link](
[Link](3));
}
}

Output
gramming

Explanation

Characters from index 3 to the end of the string are extracted.

2. substring(int startIndex, int endIndex)


Extracts characters beginning from startIndex up to endIndex - 1.

Syntax
String substring(
int startIndex,
int endIndex)

Example
class SubStringDemo2 {
public static void main(String args[]) {

String s = "Programming";

[Link](
[Link](3,7));
}
}

Output
gram

Explanation

Characters at indexes:

3, 4, 5, 6

are extracted.

Program Demonstrating Both Forms


class SubStringDemo {
public static void main(String args[]) {

String s = "Advanced Java";

[Link](
"Original String : " + s);

[Link](
"substring(9) : "
+ [Link](9));

[Link](
"substring(0,8) : "
+ [Link](0,8));
}
}

Output
Original String : Advanced Java
substring(9) : Java
substring(0,8) : Advanced

Use of substring() in String Modification


class SubstringReplace {
public static void main(String args[]) {

String org =
"This is a test";

int i =
[Link]("is");

String result =
[Link](0,i);

result =
result + "was";

result =
result +
[Link](i+2);

[Link](result);
}
}

Output
Thwas is a test

This example demonstrates how substring() can be used to extract and reconstruct portions
of a string.
Advantages of substring()
1.​ Extracts a required portion of a string.
2.​ Supports both partial and complete extraction.
3.​ Returns a new String object.
4.​ Useful in searching, parsing and string manipulation.
5.​ Widely used in text processing applications.

Compare==and equals()
with Examples.
Introduction
Java provides two ways to compare strings:

1.​ == operator
2.​ equals() method

The == operator compares object references (memory locations), whereas the equals()
method compares the contents of strings. The String class overrides the equals() method to
perform character-by-character comparison.

Difference Between == and


equals()
== Operator equals() Method

Compares references (addresses) Compares contents of strings

Checks whether two references point to the Checks whether two strings contain
same object identical characters

Operator Method of String class

Faster because only address comparison is Slightly slower because character


performed comparison is performed

Returns true only when both references refer Returns true when string contents are
to the same object equal

Does not check character data Checks character data

Example 1: Using String Literals


class LiteralDemo {
public static void main(String args[]) {

String s1 = "Java";
String s2 = "Java";

[Link](s1 == s2);
[Link]([Link](s2));
}
}

Output
true
true

Explanation

Both references point to the same object in the String Constant Pool.

Example 2: Using new Keyword


class EqualsDemo {
public static void main(String args[]) {

String s1 = "Java";

String s2 =
new String("Java");

[Link](
s1 == s2);

[Link](
[Link](s2));
}
}

Output
false
true

Explanation

●​ s1 == s2 returns false because both references point to different objects.


●​ [Link](s2) returns true because both strings contain the same characters.

Example 3: Different Strings


class CompareDemo {
public static void main(String args[]) {

String s1 = "Java";
String s2 = "Python";

[Link](
s1 == s2);

[Link](
[Link](s2));
}
}

Output
false
false

Explanation

Both references and contents are different.

Illustrate Any Five Methods of StringBuffer


Class with Examples.
Introduction
StringBuffer is a mutable class available in the [Link] package. Unlike String objects,
StringBuffer objects can be modified after creation. It provides several methods for manipulating
character sequences efficiently.

1. length()
The length() method returns the current number of characters present in the StringBuffer.

Syntax
int length()

Example
StringBuffer sb =
new StringBuffer("Hello");

[Link]([Link]());

Output
5

2. capacity()
The capacity() method returns the total allocated capacity of the StringBuffer.

Syntax
int capacity()

Example
StringBuffer sb =
new StringBuffer("Hello");

[Link]([Link]());

Output
21
3. append()
The append() method appends data at the end of the StringBuffer.

Syntax
StringBuffer append(String str)

Example
StringBuffer sb =
new StringBuffer("Java");

[Link](" Programming");

[Link](sb);

Output
Java Programming

4. insert()
The insert() method inserts data at a specified position.

Syntax
StringBuffer insert(int index,
String str)

Example
StringBuffer sb =
new StringBuffer("I Java");

[Link](2,"like ");

[Link](sb);

Output
I like Java

5. reverse()
The reverse() method reverses the contents of the StringBuffer.

Syntax
StringBuffer reverse()

Example
StringBuffer sb =
new StringBuffer("abcdef");

[Link]();

[Link](sb);

Output
fedcba

6. replace()
The replace() method replaces characters between specified indexes with a new string.

Syntax
StringBuffer replace(
int startIndex,
int endIndex,
String str)

Example
StringBuffer sb =
new StringBuffer("This is a test");

[Link](5,7,"was");

[Link](sb);
Output
This was a test

Program Demonstrating Multiple


StringBuffer Methods
class StringBufferDemo {
public static void main(String args[]) {

StringBuffer sb =
new StringBuffer("Java");

[Link](
"Length = " +
[Link]());

[Link](
"Capacity = " +
[Link]());

[Link](" Programming");

[Link](5,"Advanced ");

[Link](0,4,"Core");

[Link]();

[Link](sb);
}
}

Summary Table
Method Purpose
length() Returns number of characters

capacity() Returns buffer capacity

append() Adds characters at end

insert() Inserts characters at specified position

reverse() Reverses character sequence

replace() Replaces specified characters


Illustrate the Use of StringBuffer Methods:
append(), insert(), reverse(), and delete()
with Proper Examples
Introduction
StringBuffer is a mutable class available in the [Link] package. Unlike String objects,
StringBuffer objects can be modified after creation. It provides several methods for efficient
string manipulation such as append(), insert(), reverse(), and delete().

1. append()
The append() method is used to add characters or strings at the end of a StringBuffer object.

Syntax
StringBuffer append(String str)

Example
class AppendDemo {
public static void main(String args[]) {

StringBuffer sb =
new StringBuffer("Java");

[Link](" Programming");

[Link](sb);
}
}

Output
Java Programming

Explanation
The string " Programming" is added to the end of "Java".

2. insert()
The insert() method inserts characters or strings at a specified position.

Syntax
StringBuffer insert(int index, String str)

Example
class InsertDemo {
public static void main(String args[]) {

StringBuffer sb =
new StringBuffer("I Java");

[Link](2,"like ");

[Link](sb);
}
}

Output
I like Java

Explanation

The string "like " is inserted at index 2.

3. reverse()
The reverse() method reverses the character sequence stored in the StringBuffer object.

Syntax
StringBuffer reverse()
Example
class ReverseDemo {
public static void main(String args[]) {

StringBuffer sb =
new StringBuffer("abcdef");

[Link]();

[Link](sb);
}
}

Output
fedcba

Explanation

The characters are reversed from left to right.

4. delete()
The delete() method removes characters between specified indexes.

Syntax
StringBuffer delete(int startIndex,
int endIndex)

Example
class DeleteDemo {
public static void main(String args[]) {

StringBuffer sb =
new StringBuffer("Hello Java");

[Link](5,10);

[Link](sb);
}
}

Output
Hello

Explanation

Characters from index 5 to index 9 are deleted.

Original : Hello Java


Indexes : 0123456789

Delete(5,10)

Remaining string:

Hello

Combined Program Demonstrating All


Methods
class StringBufferMethods {
public static void main(String args[]) {

StringBuffer sb =
new StringBuffer("Java");

[Link]("Original: " + sb);

[Link](" Programming");
[Link]("After append: " + sb);

[Link](5,"Advanced ");
[Link]("After insert: " + sb);

[Link](5,14);
[Link]("After delete: " + sb);

[Link]();
[Link]("After reverse: " + sb);
}
}

Output
Original: Java
After append: Java Programming
After insert: Java Advanced Programming
After delete: Java Programming
After reverse: gnimmargorP avaJ

Summary Table
Method Purpose

append() Adds characters at the end

insert() Inserts characters at a specified position

reverse() Reverses the character sequence

delete() Removes characters from specified indexes


Describe All the String Comparison
Methods Available in Java with Examples
Introduction
Java provides several methods to compare strings. These methods are used to check equality,
lexicographical ordering, prefixes, suffixes, and case-insensitive matches. The String class
provides the following comparison methods:

1.​ equals()
2.​ equalsIgnoreCase()
3.​ startsWith()
4.​ endsWith()
5.​ compareTo()
6.​ compareToIgnoreCase()
7.​ == Operator

These methods help in comparing strings based on content, case sensitivity, and ordering.

1. equals()
The equals() method compares the contents of two strings.

Syntax
boolean equals(Object str)

Example
class EqualsDemo {
public static void main(String args[]) {

String s1 = "Java";
String s2 = "Java";
String s3 = "Python";

[Link]([Link](s2));
[Link]([Link](s3));
}
}

Output
true
false

Explanation

●​ Returns true if both strings contain the same characters.


●​ Comparison is case-sensitive.

2. equalsIgnoreCase()
The equalsIgnoreCase() method compares two strings while ignoring case differences.

Syntax
boolean equalsIgnoreCase(String str)

Example
class IgnoreCaseDemo {
public static void main(String args[]) {

String s1 = "JAVA";
String s2 = "java";

[Link](
[Link](s2));
}
}

Output
true

Explanation

Uppercase and lowercase letters are treated as equal.


3. startsWith()
The startsWith() method checks whether a string begins with a specified prefix.

Syntax
boolean startsWith(String str)
boolean startsWith(String str,
int startIndex)

Example
class StartsWithDemo {
public static void main(String args[]) {

String s = "Programming";

[Link](
[Link]("Pro"));

[Link](
[Link]("gram",3));
}
}

Output
true
true

Explanation

●​ First statement checks the beginning of the string.


●​ Second statement starts checking from index 3.

4. endsWith()
The endsWith() method checks whether a string ends with a specified suffix.

Syntax
boolean endsWith(String str)
Example
class EndsWithDemo {
public static void main(String args[]) {

String s = "Programming";

[Link](
[Link]("ing"));
}
}

Output
true

5. compareTo()
The compareTo() method compares two strings lexicographically (dictionary order).

Syntax
int compareTo(String str)

Return Values

Value Meaning

0 Strings are equal

Positive Invoking string is greater

Negative Invoking string is smaller

Example
class CompareToDemo {
public static void main(String args[]) {

String s1 = "Apple";
String s2 = "Ball";

[Link](
[Link](s2));
}
}

Output
-1

Explanation

Since "Apple" comes before "Ball" alphabetically, a negative value is returned.

6. compareToIgnoreCase()
This method performs lexicographical comparison while ignoring case differences.

Syntax
int compareToIgnoreCase(String str)

Example
class CompareIgnoreDemo {
public static void main(String args[]) {

String s1 = "JAVA";
String s2 = "java";

[Link](
[Link](s2));
}
}

Output
0
Explanation

Both strings are considered equal after ignoring case.

7. == Operator
The == operator compares object references rather than contents.

Example
class DoubleEqualDemo {
public static void main(String args[]) {

String s1 = "Java";
String s2 = new String("Java");

[Link](s1 == s2);
[Link]([Link](s2));
}
}

Output
false
true

Explanation

●​ == compares memory addresses.


●​ equals() compares actual string contents.

Summary Table
Method Purpose
equals() Compares string contents

equalsIgnoreCase() Compares contents ignoring case

startsWith() Checks starting characters

endsWith() Checks ending characters

compareTo() Lexicographical comparison

compareToIgnoreCase() Lexicographical comparison ignoring case

== Compares references (addresses)

Comprehensive Program
class StringComparisonDemo {
public static void main(String args[]) {

String s1 = "Java";
String s2 = "JAVA";
String s3 = "Programming";

[Link]([Link]("Java"));

[Link](
[Link](s2));

[Link](
[Link]("Pro"));

[Link](
[Link]("ing"));

[Link](
[Link]("Python"));

[Link](
[Link](s2));
}
}

Output
true
true
true
true
negative value
0

Conclusion
Java provides several string comparison methods such as equals(), equalsIgnoreCase(),
startsWith(), endsWith(), compareTo(), and compareToIgnoreCase(). These
methods allow comparison of string contents, prefixes, suffixes, and lexicographical ordering.
The == operator compares object references and should not be used when content comparison
is required.
What is String in Java? Illustrate a Java
Program that Demonstrates Any Four
Constructors of String Class.
Introduction
A String is a sequence of characters enclosed within double quotes. In Java, String is both a
class and a data type. It is a predefined public final class present in the [Link]
package. String objects are immutable, which means their contents cannot be changed once
they are created.

Example

String s = "Java";

Features of String Class


1.​ String is a non-primitive data type.
2.​ String objects are immutable.
3.​ String class is present in [Link] package.
4.​ String class is a final class and cannot be inherited.
5.​ String objects can be created using literals or the new keyword.

Program Demonstrating Four


Constructors of String Class
class StringConstructorsDemo {

public static void main(String args[]) {

// Constructor 1 : Default Constructor


String s1 = new String();

// Constructor 2 : Character Array Constructor

char ch[] = {'J','a','v','a'};

String s2 = new String(ch);

// Constructor 3 : Character Array Subset Constructor

char arr[] = {'P','r','o','g','r','a','m'};

String s3 = new String(arr,0,4);

// Constructor 4 : String Object Constructor

String s4 = new String(s2);

[Link]("s1 = " + s1);

[Link]("s2 = " + s2);

[Link]("s3 = " + s3);

[Link]("s4 = " + s4);

Output
s1 =

s2 = Java

s3 = Prog
s4 = Java

Explanation of Constructors
1. Default Constructor
Syntax

String s = new String();

Behavior

●​ Creates an empty String object.


●​ Length of the string is zero.

Example

String s1 = new String();

Output:

(empty string)

2. Character Array Constructor


Syntax

String(char chars[])

Example

char ch[] = {'J','a','v','a'};

String s2 = new String(ch);

Output:
Java

Behavior

Converts the entire character array into a String object.

3. Character Array Subset Constructor


Syntax

String(char chars[],

int startIndex,

int numChars)

Example

char arr[] =

{'P','r','o','g','r','a','m'};

String s3 =

new String(arr,0,4);

Output:

Prog

Behavior

●​ Starts at index 0.
●​ Extracts 4 characters.
●​ Creates the string "Prog".

4. String Object Constructor


Syntax

String(String strObj)

Example

String s4 =

new String(s2);

Output:

Java

Behavior

Creates a new String object using another String object.

Summary Table

Constructor Purpose

String() Creates an empty string

String(char[]) Creates string from character array

String(char[], int, int) Creates string from part of character array

String(String) Creates string from another string


Explain the Following
Character Extraction
Methods:

charAt() , getChars()
, and toCharArray()
Introduction
The String class provides several methods to extract characters from a String object. These
methods are useful when individual characters or groups of characters need to be accessed
and processed. The important character extraction methods are:

1.​ charAt()
2.​ getChars()
3.​ toCharArray()

These methods are used to retrieve one character, multiple characters, or all characters from a
string.

1. charAt() Method
The charAt() method is used to extract a single character from a specified position in a string.

Syntax

char charAt(int index)


Where:

●​ index specifies the position of the character.


●​ Index starts from 0.

Example Program

class CharAtDemo {

public static void main(String args[]) {

String s = "Java";

char ch = [Link](2);

[Link](ch);

Output

Explanation

J a v a

0 1 2 3

Character at index 2 is:

Hence charAt(2) returns 'v'.


2. getChars() Method
The getChars() method is used to extract multiple characters from a string and store them
into a character array.

Syntax

void getChars(int sourceStart,

int sourceEnd,

char target[],

int targetStart)

Parameters

●​ sourceStart → Starting index in source string.


●​ sourceEnd → Ending index (excluded).
●​ target[] → Destination character array.
●​ targetStart → Starting position in destination array.

Example Program

class GetCharsDemo {

public static void main(String args[]) {

String s =

"This is a demo of getChars";

int start = 10;

int end = 14;

char buf[] =
new char[end - start];

[Link](start,end,buf,0);

[Link](buf);

Output

demo

Explanation

String:

This is a demo of getChars

↑ ↑

10 14

Characters from index 10 to 13 are copied into the character array.

Result:

demo

3. toCharArray() Method
The toCharArray() method converts the entire string into a character array.

Syntax

char[] toCharArray()
Example Program

class ToCharArrayDemo {

public static void main(String args[]) {

String s = "Java";

char ch[] =

[Link]();

for(int i=0;i<[Link];i++) {

[Link](ch[i]);

Output

Explanation

The complete string:

Java

is converted into:
{'J','a','v','a'}

which can then be processed like a normal character array.

Comparison of Character Extraction


Methods
Method Purpose Return Type

charAt() Extracts a single character char

getChars() Extracts multiple characters into an array void

toCharArray() Converts entire string into character array char[]

Comprehensive Program
class CharacterExtraction {

public static void main(String args[]) {

String s = "Programming";

// charAt()

[Link](
"charAt(3) = " +

[Link](3));

// getChars()

char buf[] = new char[4];

[Link](3,7,buf,0);

[Link](

"getChars = " +

new String(buf));

// toCharArray()

char arr[] =

[Link]();

[Link](

"toCharArray = ");

for(char c : arr)

[Link](c + " ");

Output

charAt(3) = g
getChars = gram

toCharArray =

Programming

Conclusion
The String class provides character extraction methods such as charAt(), getChars(), and
toCharArray(). The charAt() method extracts a single character, getChars() extracts
multiple characters into a character array, and toCharArray() converts the entire string into a
character array. These methods are widely used in string processing and text manipulation
applications.

You might also like