Module 2-2
Module 2-2
String s1 = "Java";
[Link](" Programming");
[Link](s1);
}
}
Output
Java
Explanation
The statement
[Link](" Programming");
However, since it is not assigned back to s1, the original object "Java" remains unchanged.
Java
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.
Example:
String s1 = "Java";
String s2 = "Java";
"Java"
/ \
s1 s2
If strings were mutable, changing through one reference would affect all references.
Immutability avoids this problem.
2. Security
3. Thread Safety
Example:
Multiple threads can safely access the same String object because its contents cannot change.
No synchronization is required.
4. HashMap Support
[Link]("Java",100);
If String contents could change, the hash code would also change, causing retrieval failures.
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.
● append()
● insert()
● replace()
● reverse()
StringBuffer internally uses a dynamic character buffer which can grow automatically whenever
additional space is required.
Example 1: append()
class AppendDemo {
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 {
StringBuffer sb =
[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 {
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.
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
[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
[Link](" Programming");
[Link](sb);
Output
Java Programming
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()
Memory efficient for read-only Less efficient due to More efficient and
strings synchronization overhead high-performance
String s = "Java";
s = s + " Programming";
[Link](" Programming");
[Link](" Programming");
Output
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.
Return Values
Example
String s1 = "chutiya";
String s2 = "anish";
[Link]([Link](s2));
Output:
Positive Value
Because:
class Main {
String arr[] = {
"chutiya",
"anish",
"dhurandhar",
"bruno"
};
[Link]("Before Sorting:");
[Link]([Link](arr));
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:
After Sorting:
Step 1
"chutiya".compareTo("anish")
Step 2
"chutiya".compareTo("bruno")
c>b
Step 3
"dhurandhar".compareTo("chutiya")
d>c
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.
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[]) {
[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[]) {
[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
Example
String s = new String();
[Link](s);
Example
char ch[] =
{'J','a','v','a'};
String s =
new String(ch);
[Link](s);
Output:
Java
Example
char ch[] =
{'a','b','c','d','e','f'};
String s =
new String(ch,2,3);
[Link](s);
Output:
cde
String s2 =
new String(s1);
[Link](s2);
Output:
Java
Example
byte b[] =
{65,66,67,68};
String s =
new String(b);
[Link](s);
Output:
ABCD
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
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
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.
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
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.
[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
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.
Checks whether two references point to the Checks whether two strings contain
same object identical characters
Returns true only when both references refer Returns true when string contents are
to the same object equal
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.
String s1 = "Java";
String s2 =
new String("Java");
[Link](
s1 == s2);
[Link](
[Link](s2));
}
}
Output
false
true
Explanation
String s1 = "Java";
String s2 = "Python";
[Link](
s1 == s2);
[Link](
[Link](s2));
}
}
Output
false
false
Explanation
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
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
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
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
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
Delete(5,10)
Remaining string:
Hello
StringBuffer sb =
new StringBuffer("Java");
[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
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
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
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
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
Example
class CompareToDemo {
public static void main(String args[]) {
String s1 = "Apple";
String s2 = "Ball";
[Link](
[Link](s2));
}
}
Output
-1
Explanation
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
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
Summary Table
Method Purpose
equals() Compares string contents
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";
Output
s1 =
s2 = Java
s3 = Prog
s4 = Java
Explanation of Constructors
1. Default Constructor
Syntax
Behavior
Example
Output:
(empty string)
String(char chars[])
Example
Output:
Java
Behavior
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".
String(String strObj)
Example
String s4 =
new String(s2);
Output:
Java
Behavior
Summary Table
Constructor Purpose
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
Example Program
class CharAtDemo {
String s = "Java";
char ch = [Link](2);
[Link](ch);
Output
Explanation
J a v a
0 1 2 3
Syntax
int sourceEnd,
char target[],
int targetStart)
Parameters
Example Program
class GetCharsDemo {
String s =
char buf[] =
new char[end - start];
[Link](start,end,buf,0);
[Link](buf);
Output
demo
Explanation
String:
↑ ↑
10 14
Result:
demo
3. toCharArray() Method
The toCharArray() method converts the entire string into a character array.
Syntax
char[] toCharArray()
Example Program
class ToCharArrayDemo {
String s = "Java";
char ch[] =
[Link]();
for(int i=0;i<[Link];i++) {
[Link](ch[i]);
Output
Explanation
Java
is converted into:
{'J','a','v','a'}
Comprehensive Program
class CharacterExtraction {
String s = "Programming";
// charAt()
[Link](
"charAt(3) = " +
[Link](3));
// getChars()
[Link](3,7,buf,0);
[Link](
"getChars = " +
new String(buf));
// toCharArray()
char arr[] =
[Link]();
[Link](
"toCharArray = ");
for(char c : arr)
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.