JAVA Module 2
JAVA Module 2
Module 2
String Handling
String Handling :The String Constructors, String Length, Special String Operations, Character
Extraction, String Comparison, Searching Strings, Modifying a String, Data Conversion Using
valueOf( ), Changing the Case of Characters Within a String, joining strings, Additional String
Methods, StringBuffer , StringBuilder
in
The String class supports several constructors.
a. To create an empty String
the default constructor is used.
Ex: String s = new String();
.
will create an instance of String with no characters in it.
ex:
ud
b. To create a String initialized by an array of characters, use the constructor
shown here:
String(char chars[ ])
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
lo
c. To specify a subrange of a character array as an initializer using the following
constructor:
String(char chars[ ], int startIndex, int numChars)
Here, startIndex specifies the index at which the subrange begins, and
uc
class MakeString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new
String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
in
As you can see, s1 and s2 contain the same string.
.
8-bit bytesconstructed from the ASCII character set. Because 8-bit ASCII
ud
strings are common, the String class provides constructors that initialize a
string when given a byte array.
Ex: String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Note:
String can be constructed by using string
literals.String s1=”Hello World”
in
String concatenation can be done using + operator. With other data type also.
String Length
1. The length of a string is the number of characters that it contains. To
.
obtainthis value, call the length( ) method,
2. Syntax:
ud
int length( )
3. Example
char chars[] = { 'a', 'b', 'c' }; String s = new String(chars);
System.out.println(s.length());// 3
lo
toString()
1. Every class implements toString( ) because it is defined by
Object.However, the default Implementation of toString() is
sufficient.
uc
2. For most important classes that you create, will want to override
toString()and provide your own string representations.
String toString( )
3. To implement toString( ), simply return a String object that contains
the human-readable string that appropriately describes an object of your
class.
vt
4. By overriding toString() for classes that you create, you allow them to
befully integrated into Java’s programming environment. For example,
theycan be used in print() and println() statements and in
concatenation expressions.
class Box
{
double width; double height; double
depth;Box(double w, double h, double
d)
{
width = w; height = h; depth = d;
}
class toStringDemo
in
{
public static void main(String args[])
{
Box b = new Box(10, 12, 14);
String s = "Box b: " + b;
.
System.out.println(b);
}
ud
System.out.println(s);
}
were a character array, many of the String methods employ an index (or
offset) into the string for their operation. Like arrays, the string indexes
beginat zero.
A. charAt( )
1. description:
To extract a single character from a String, you can refer directly to
vt
3. example,
char ch;
ch = "abc".charAt(1);
assigns the value “b” to
ch.
Java Program
in
// Get the character at index 7
char characterAtIndex7 = sampleString.charAt(7);
.
System.out.println("The character at index 7 is: " + characterAtIndex7);
Output:
uc
B. getChars( )
vt
1. to extract more than one character at a time, you can use the
getChars()method.
2. Syntax
void getChars(int sourceStart, int sourceEnd, char target[ ],
inttargetStart)
Java Program
in
// Print the destinationArray
System.out.print("The characters copied to destinationArray are: ");
for (char c : destinationArray) {
System.out.print(c);
.
}
}
ud
}
Output:
System.out.println();
}
Here is the output of this program:
Demo
C. getBytes( )
1. This method is called getBytes( ), and it uses the default character-to-
byteconversions provided by the platform.
Syntax:
byte[ ] getBytes( )
Other forms of getBytes( ) are also available.
2. getBytes( ) is most useful when you are exporting a String value into an
environment that does not support 16-bit Unicode characters. For
example,most Internet protocols and text file formats use 8-bit ASCII
for all text interchange.
Java Program
public class GetBytesExample
{
public static void main(String[] args)
{
String sampleString = "Hello, World!";
in
// Get bytes from the string using the platform's default charset
byte[] byteArray = sampleString.getBytes();
.
for (byte b : byteArray)
ud {
}
System.out.print(b + " ");
System.out.println();
// Get bytes from the string using a specified charset (e.g., UTF-8)
lo
try
{
byte[] utf8ByteArray = sampleString.getBytes("UTF-8");
// Print the bytes
uc
}
catch (java.io.UnsupportedEncodingException e)
{
System.out.println("The specified charset is not supported.");
}
}
}
Output:
D. toCharArray( )
If you want to convert all the characters in a String object into a
characterarray, the easiest way is to call toCharArray( ).
in
string.It has this general form:
char[ ] toCharArray( )
Java Program
.
public class ToCharArrayExample
{
ud {
public static void main(String[] args)
String sampleString = "Hello, World!";
// Convert the string to a character array
char[] charArray = sampleString.toCharArray();
// Print the characters in the array
lo
System.out.print("The characters in the array are: ");
for (char c : charArray) {
System.out.print(c + " ");
}
System.out.println();
}
uc
}
Output:
The characters in the array are: H e l l o , W o r l d !
String Comparision
String comparison in Java can be performed using several methods, each serving different
vt
purposes and offering varying degrees of control over how the comparison is executed. Here
are some common ways to compare strings in Java:
The String class includes several methods that compare strings or substrings within
strings.
a. equals ( ):
To compare two strings for equality, use equals( ).
It has this general form:
boolean equals(Object str)
Here, str is the String object being compared with the invoking String object. It
returns true if the strings contain the same characters in the same order, and false
otherwise. The comparison is case-sensitive.
The equals( ) method compares the content of two strings for equality. It is case-
sensitive.
public class EqualsExample
{
public static void main(String[] args)
{
String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";
in
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // false
}
}
.
Output: true
false
b. equalsIgnoreCase( )
ud
To perform a comparison that ignores case differences, call equalsIgnoreCase( ).
When it compares two strings, it considers A-Z to be thesame as a-z.
It has this general form:
lo
boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the invoking String object. It, too,
returns true if the strings contain the same characters in the same order, and false
otherwise.
Example 1:
uc
{
public static void main(String[] args)
{
vt
{
System.out.println("The strings are equal.");
}
else
{
System.out.println("The strings are not equal.");
}
in
}
}
.
Example2 :
{
ud
public class EqualsIgnoreCaseFalseExample
{
lo
// Define two strings
String str1 = "HelloWorld";
String str2 = "HelloJava";
uc
if (areEqual)
{
System.out.println("The strings are equal (ignoring case).");
}
else
{
System.out.println("The strings are not equal.");
}
}
}
Output: The strings are not equal.
C. regionmatches( )
in
intnumChars)
.
3. For both versions, startIndex specifies the index at which the region begins
within the invoking String object.
ud
The String being compared is specified by str2. The index at which the
comparison will start within str2 is specified by str2 StartIndex. The length
ofthe substring being compared is passed in numChars.
Here is a simple program that demonstrates the use of the regionMatches() method.
uc
I'll provide two versions: one where regionMatches() returns true and another
where it returns false.
Program 1: regionMatches() Returns true
public class RegionMatchesTrueExample
vt
{
public static void main(String[] args)
{
// Define two strings
String str1 = "HelloWorld";
String str2 = "World";
}
else
{
in
System.out.println("The regions do not match.");
}
.
}
ud
Output: The region matches
Program 2: regionMatches() Returns false
public class RegionMatchesFalseExample
{
lo
public static void main(String[] args)
{
// Define two strings
uc
{
System.out.println("The regions match.");
}
else
{
in
▪ endsWith( ) determines whether the String in question ends
with aspecified string.
▪ Syntax
• boolean startsWith(String str);
• boolean endsWith(String str);
.
• Here, str is the String being tested.
ud
• If the string matches, true is returned.
Otherwise, false is returned.
The startsWith() method in Java is used to check if a string begins with a specified prefix.
Here are two simple programs that demonstrate the use of the startsWith() method: one where
the method returns true and another where it returns false.
Program 1:
lo
public class StartsWithTrueExample
{
public static void main(String[] args)
uc
{
// Define the string
String str = "HelloWorld";
vt
}
else
{
System.out.println("The string does not start with the prefix.");
}
}
}
in
Output: The string starts with the prefix
Program 1: StartsWithTrueExample
.
Define Prefix: prefix is "Hello".
ud
Check Prefix: str.startsWith(prefix) returns true because str starts with "Hello".
Print Result: The program prints "The string starts with the prefix."
Program2 :
else
{
System.out.println("The string does not start with the prefix.");
}
}
}
Program 2: StartsWithFalseExample
in
Output: The string does not start with the prefix
Define String: str is "HelloWorld".
.
Check Prefix: str.startsWith(prefix) returns false because str does not start with "World".
endswith ( ) method:
ud
Print Result: The program prints "The string does not start with the prefix."
The endsWith() method in Java is used to check if a string ends with a specified suffix. Here
are two simple programs that demonstrate the use of the endsWith() method: one where the
method returns true and another where it returns false.
lo
Program 1: endsWith() Returns true
public class EndsWithTrueExample
{
uc
in
}
Output: The string ends with the suffix
Program 1: EndsWithTrueExample
.
Define String: str is "HelloWorld".
ud
Define Suffix: suffix is "World".
Check Suffix: str.endsWith(suffix) returns true because str ends with "World".
Print Result: The program prints "The string ends with the suffix."
}
else
{
System.out.println("The string does not end with the suffix.");
}
}
}
in
Output: The string does not end with the suffix
Program 2: EndsWithFalseExample
.
Define Suffix: suffix is "Hello
ud
Check Suffix: str.endsWith(suffix) returns false because str does not end with "Hello".
Print Result: The program prints "The string does not end with the suffix."
e. equals( ) Versus ==
It is important to understand that the equals( ) method and the == operator
perform two different operations.
lo
the equals( ) method compares the characters inside a String object.
The == operator compares two object references to see whether they refer to the
same instance.
class EqualsNotEqualTo
uc
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
vt
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // true
== Operator
The == operator in Java checks whether two object references point to the same
memory location, i.e., whether they refer to the same object. When applied to strings, it
checks whether two string variables refer to the same string object in memory.
in
System.out.println(str1 == str2); // true (because of string literal pooling)
System.out.println(str1 == str3); // false (different memory locations)
.
Note:
f. compareTo( )
▪
ud
equals() compares the contents of two strings.
Sorting applications, you need to know which is less than, equal to, or
greater than the next.
▪
lo
A string is less than another if it comes before the other in dictionary
order. A string is greater than another if it comes after the other in
dictionary order. The String method compareTo() serves this purpose.
▪ It has this general form:
• int compareTo(String str)
uc
• Here, str is the String being compared with the invoking String. The result
of the comparison is returned and is interpreted,
▪ Less than zero when invoking string is less than str.
▪ Greater than zero when invoking string is greater than str.
▪ Zero The two strings are equal.
The compareTo() method in Java is used to compare two strings lexicographically. It
vt
If the first string is lexicographically less than the second string, it returns a negative
integer.
If the strings are equal, it returns 0.
If the first string is lexicographically greater than the second string, it returns a positive
integer.
in
if (result < 0)
{
.
}
{
ud
else if (result > 0)
}
lo
else
{
System.out.println(str1 + " and " + str2 + " are equal lexicographically.");
uc
}
}
vt
If the characters differ, the string with the lower Unicode value at that position is
considered "smaller" in lexicographical order.
If one string ends before the other and all corresponding characters are equal, the
shorter string is considered "smaller".
For example:
"apple" comes before "banana" lexicographically because 'a' comes before 'b'.
"apple" comes after "ant" lexicographically because 'p' comes after 'n', even though 'p'
comes after 'n'.
in
"apple" and "apple" are considered equal lexicographically because they are identical.
.
5. Searching String
ud
A. indexOf( ) and lastIndexOf( )
1. indexOf( ) Searches for the first occurrence of a character orsubstring.
7. To search for the first or last occurrence of a substring, use int indexOf(String
str) int lastIndexOf(String str) Here, str specifiesthe substring.
vt
8. You can specify a starting point for the search using these forms: int indexOf(int
ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
9. int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex)
Here, startIndex specifies the index at which point the search begins.
10. For indexOf( ), the search runs from startIndex to the end of
the string. For lastIndexOf( ), the search runs from startIndex to zero. The
following example shows how to use the various index methods to search inside
of Strings:
For Strings: In the context of strings, indexOf() searches the string for a specified substring
and returns the position of the first occurrence of that substring. If the substring is not found,
it returns -1.
console.log(str.indexOf("world")); // Output: 7
in
console.log(str.indexOf("Earth")); // Output: -1 (not found)
or Arrays: In the context of arrays, indexOf() searches the array for a specified item and
returns the index of the first occurrence of that item. If the item is not found, it returns -1.
.
Javascript
ud
let arr = [1, 2, 3, 4, 5];
console.log(arr.indexOf(3)); // Output: 2
Java Program
lo
public class IndexOfDemo
{
uc
if (array[i] == value)
in
{
return i;
.
}
}}
} ud
return -1; // Value not found in the array
Output:
lo
Index of 'world' in string : 7
Index of 3 in array: 2
uc
The lastIndexOf() method is similar to the indexOf() method but searches for the last
occurrence of a specified value instead of the first occurrence. Here's a small Java program
demonstrating the use of the lastIndexOf() method for both a string and an array.
}
// Helper method to find the last index of an element in an array
public static int lastIndexOf(int[] array, int value)
in
{
for (int i = array.length - 1; i >= 0; i--)
.
if (array[i] == value)
{
}
ud
return i;
}
lo
return -1; // Value not found in the array
}
uc
Output:
5. Modifying a String
String objects are immutable, whenever you want to modify a String, you must either
copy it into a StringBuffer or StringBuilder, or use one of the following String methods,
which will construct a new copy of the string with your modifications complete.
The substring() method in Java is used to extract a part of a string. It has two
overloaded versions:
substring(int beginIndex): Returns a new string that is a substring of the original string,
starting from the specified index to the end of the string.
substring(int beginIndex, int endIndex): Returns a new string that is a substring of the
original string, starting from the specified index to the specified end index (exclusive).
Here's a small Java program that demonstrates the use of both versions of the substring()
method:
Java Program:
in
String str = "Hello, world!";
// Using substring(beginIndex)
String subStr1 = str.substring(7);
.
System.out.println("Substring from index 7: " + subStr1); // Output: "world!"
ud
// Using substring(beginIndex, endIndex)
}
uc
Output:
Substring from index 7: world!
Substring from index 0 to 5: Hello
Substring from index 7 to 12: world
vt
The concat() method in Java is used to concatenate, or join together, two strings. This method
appends the specified string to the end of the current string.
Here's a small Java program that demonstrates the use of the concat() method:
public class ConcatDemo
{
in
// Additional example
String str3 = " Have a great day!";
.
// Printing the final result
ud
System.out.println("Final Concatenated String: " + finalString); // Output: "Hello,
world! Have a great day!"
}
}
The first replaces all occurrences of one character in the invoking string with another
character.
Syntax:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by
replacement. The resulting string is returned.
vt
Example
String s = "Hello".replace('l', 'w');puts the string
“Hewwo” into s.
The second form of replace( ) replaces one character sequence with another. It has this
general form:
String replace(CharSequence original, CharSequence replacement)
in
String replacement = "Universe";
// Use the replace() method to create a new string with the replacements
.
String modifiedString = originalString.replace(toReplace, replacement);
ud
// Display the original and modified strings
}
lo
}
Output:
uc
trim( )
The trim() method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed.
vt
Syntax:
String trim( )Example:
String s = " Hello World".trim();
This puts the string “Hello World” into s.
The trim( ) method is quite useful when you process user commands.
The trim() method in Java is used to remove leading and trailing whitespace from a
string. It is a simple and commonly used method for cleaning up strings before
processing them further.
Here's a simple Java program that demonstrates the use of the trim() method:
Java Program:
public class TrimExample
{
public static void main(String[] args)
{
// Define a string with leading and trailing spaces
String originalString = " Hello, World! ";
in
// Use the trim() method to remove leading and trailing spaces
String trimmedString = originalString.trim();
.
}
}
Output:
ud
Original string: " Hello, World! "
2. valueOf( ) is also overloaded for type Object, so an object of any class type you create
can also be used as an argument
Syntax:
vt
valueOf( ) is called when a string representation of some other typeof data is needed.
example, during concatenation operations.
Any object that you pass to valueOf( ) will return the result of a call to the object’s
toString( ) method.
There is a special version of valueOf() that allows you tospecify asubset of a char array.
Syntax:
static String valueOf(char chars[ ], int startIndex, int numChars)
Here, chars is the array that holds the characters, startIndex is the index into the array of
characters at which the desired substring begins, and numChars specifies the length of the
substring.
public class SimpleValueOfExample
in
{
// Integer to String
.
int intValue = 100;
ud
String intString = String.valueOf(intValue);
// Double to String
// Boolean to String
// Char to String
} }
Output:
Char to String: Z
toLowerCase( )
1. converts all the characters in a string from uppercase to lowercase.
2. This method return a String object that contains the lowercase equivalent of the
in
invoking String.
Syntax
.
String toLowerCase( )
Java Program
ud
public class ToLowerCaseExample
{
public static void main(String[] args)
lo
{
// Define the original string
String originalString = "Hello, World!";
Output:
Original string: Hello, World!
Lowercase string: hello, world!
A. toUpperCase()
Syntax
String toUpperCase( )
In Java, the toUpperCase() method is used to convert all characters in a string to uppercase.
in
{
// Create a string
.
ud
// Convert all characters to uppercase
}
uc
Output:
StringBuffer
StringBuffer is a peer class of String that provides much of the functionality of strings.
Asyou know, String represents fixed-length, immutable character sequences.
This makes StringBuffer suitable for situations where you need to modify strings
frequently without creating new objects each time.
in
stringBuffer.append(" World");
.
stringBuffer.insert(5, ", ");
// Replace text ud
stringBuffer.replace(6, 11, "there");
// Delete characters
stringBuffer.delete(11, 12);
lo
// Print the modified string
In this example:
multithreaded environments. If you don't need thread safety, you can use the
StringBuilder class, which provides similar functionality but is not synchronized,
resulting in better performance in single-threaded scenarios
in
StringBuffer may have characters and substrings inserted in the middle or appended to
theend.
StringBuffer will automatically grow to make room for such additions and often has
.
morecharacters pre allocated than are actually needed, to allow room for growth.
ud
StringBuffer Constructors
StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
lo
StringBuffer(String str)
StringBuffer(CharSequence chars)
a. The default constructor (the one with no parameters) reserves room for 16
characters without reallocation.
uc
b. The second version accepts an integer argument that explicitly sets the size of
thebuffer.
c. The third version accepts a String argument that sets the initial contents of the
StringBuffer object and reserves room for 16 more characters without
reallocation.
vt
in
int length = str.length();
// Print the length of the string
System.out.println("Length of the string: " + length);
.
// Output: Length of the string: 13
}
Output:
}
ud
Length of the string: 13
lo
Java Program on capacity( )
public class CapacityExample
{
uc
}
We create a StringBuffer object without specifying an initial capacity. By default, it
initializes with a capacity of 16.
We append the string "Hello World" to the StringBuffer, which increases its capacity
if needed to accommodate the new data.
We use the capacity() method of the StringBuffer class to get the current capacity.
The current capacity is stored in the variable capacity.
in
We then print the current capacity using System.out.println().
Output: Current Capacity: 16
ensureCapacity( )
.
a. If you want to pre allocate room for a certain number of characters after a
StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of
thebuffer. ud
b. This is useful if you know in advance that you will be appending a large number
ofsmall strings to a StringBuffer.
Syntax
void ensureCapacity(int capacity)
lo
Here, capacity specifies the size of the buffer.
The ensureCapacity() method in Java is used to ensure that the StringBuffer or StringBuilder
has a minimum capacity specified by the parameter. If the current capacity of the buffer is
uc
less than the specified minimum capacity, the buffer's capacity is increased to the specified
minimum capacity. Otherwise, the capacity remains unchanged.
Java Program
public class EnsureCapacityExample
{
vt
in
We print the current capacity after ensuring the capacity.
Output:
Initial Capacity: 10
.
Current Capacity after ensuring: 20
setLength( )
ud
To set the length of the buffer with in a StringBufferobject,
Syntax:
If you call setLength( ) with a value less than the current value returned by length(), then
thecharacters stored beyond the new length will be lost.
In Java, the setLength() method is used to set the length of a StringBuffer or
StringBuilder object to a specified value. If the new length is greater than the current
length, the additional characters are filled with null characters ('\0'). If the new length is
vt
smaller than the current length, the content of the buffer is truncated to fit the new length.
Java Program
in
stringBuffer.setLength(5);
.
System.out.println("Content after setting length: " + stringBuffer);
}
}
ud
System.out.println("Length after setting length: " + stringBuffer.length());
lo
Explanation:
We print the content and length of the StringBuffer after setting the length.
Output:
vt
Initial Length: 13
usingsetCharAt( ).
b. Syntax
char charAt(int where)
void setCharAt(int where, char ch)
c. For charAt( ), where specifies the index of the character being obtained.
d. For setCharAt( ), where specifies the index of the character being set, and ch
specifies the new value of that character.
In Java, the charAt() method is used to retrieve the character at a specified index in
a string. It belongs to the String class. The indexing starts from 0, meaning the first
in
character is at index 0, the second character is at index 1, and so on. Here's how
you can use it:
.
public static void main(String[] args)
{
ud
// Create a string
String str = "Hello, World!";
}
}
setChar( ) method
vt
The setCharAt() method, on the other hand, is a method of the StringBuffer class
(or StringBuilder in case of non-synchronized operations), which is used to modify
the character at a specified index in a string. It allows you to replace the character
at the given index with a new character. Here's how you can use it:
public class SetCharAtExample
{
public static void main(String[] args)
{
// Create a StringBuffer
StringBuffer stringBuffer = new StringBuffer("Hello, World!");
// Set the character at index 7 to 'G'
stringBuffer.setCharAt(7, 'G');
// Print the modified string
System.out.println("Modified string: " + stringBuffer); // Output: Modified string:
Hello, Gold!
}
in
}
Output: Modified string: Hello, Gold!
getChars( ) method
.
a. To copy a substring of a StringBuffer into an array, use the getChars( )
method.Syntax
Syntax
ud
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring, and
sourceEndspecifies an index that is one past the end of the desired substring.
lo
b. This means that the substring contains the characters from sourceStart
throughsourceEnd–1.
The index within target which the substring will be copied is passed in targetStart.
d. Care must be taken to assure that the target array is large enough to hold the
numberof characters in the specified substring.
int sourceStart = 0;
int sourceEnd = 5;
int targetStart = 0;
Output:Hello
in
StringBuffer getChars Method:
The method getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) copies characters
from the StringBuffer into the destination character array dst.
.
srcBegin: The starting index in the source StringBuffer.
ud
srcEnd: The ending index in the source StringBuffer (exclusive).
dstBegin: The starting index in the destination array where copying begins.
Specifies sourceStart as 0 and sourceEnd as 5 to copy the first five characters ("Hello").
uc
Initializes a target character array target with a length of 5 to hold the copied characters.
Calls the getChars method to copy the specified characters from exampleBuffer to target.
append( )
The append() method concatenates the string representation of any other type of
datato the end of the invoking StringBuffer object. It has several overloaded
versions. Here are a few of its forms:
StringBuffer append(String str)
in
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
.
s = sb.append("a =
}
}
ud
").append(a).append("!").toString();
System.out.println(s);
lo
Output
a = 42!
insert( )
uc
class insertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
in
}
Output:
I like Java!
.
reverse( )
ud
You can reverse the characters within a StringBuffer object using reverse( ),
shown here:StringBuffer reverse( )
This method returns the reversed object on which it was
lo
called.The following program demonstrates reverse( )
class ReverseDemo
{
public static void main(String args
uc
[]) {
StringBuffer s = new
StringBuffer("abcdef");
System.out.println(s); s
vt
.reverse();
System.out.println(s
); }
}
Output
:
abcdef
fedcba
Prof. Radha R, Dept. of ISE, SVIT Page 41
Module 2: String Handling
in
Here, startIndex specifies the index of the first character to remove, and endIndex
specifies an index one past the last character to remove.
Thus, the substring deleted runs from startIndex to endIndex–1. The resulting
StringBufferobject is returned.
.
The deleteCharAt( ) method deletes the character at the index specified by loc. It returns
ud
theresulting StringBuffer object.
// Demonstrate delete() and deleteCharAt()
class deleteDemo
{
lo
public static void main(String args[])
{
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
vt
a. You can replace one set of characters with another set inside a StringBuffer object
bycalling replace( ).
b. Syntax
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex.
c. Thus, the substringatstartIndexthroughendIndex–1 is replaced.The replacement
stringis passed in str.
The resulting StringBuffer object is
in
returned.class replaceDemo
{
public static void main(String args[])
.
{
ud
StringBuffer sb = new StringBuffer("This is a
test.");sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
lo
}
Here is the output:
After replace: This was a test.
uc
substring( )
1. It has the following two
forms:Syntax
String substring(int startIndex)
vt
1. J2SE 5 adds a new string class to Java’s already powerful string handling
capabilities.This new class is called StringBuilder.
2. It is identical to StringBuffer except for one important difference: it is
1. int codePointAt(int i )
Returns the Unicode code point at the location specified by i.
2. int codePointBefore(int i )
Returns the Unicode code point at the location that precedes that specified by i.
3. int codePointCount(int start , int end )
in
Returns the number of code points in the portion of the invoking String that
arebetween start and end– 1.
4. boolean contains(CharSequence str )
Returns true if the invoking object contains the string specified by str . Returns
.
false,otherwise.
5. boolean contentEquals(CharSequence str )
ud
Returns true if the invoking string contains the same string as str. Otherwise,
returns false.
6. boolean contentEquals(StringBuffer str )
Returns true if the invoking string contains the same string as str. Otherwise,
returns false.
7. static String format(String fmtstr , Object ... args )
lo
Returns a string formatted as specified by fmtstr.
8. static String format(Locale loc , String fmtstr , Object ... args )
Returns a string formatted as specified by fmtstr.
9. boolean matches(string regExp )
Returns true if the invoking string matches the regular expression passed in
uc
fully decomposed. Otherwise, if max contains a nonzero value, the last entry in the
returnedarray contains the remainder of the invoking string. If max is zero, the
invoking stringis fully decomposed.
15. CharSequence subSequence(int startIndex , int stopIndex )
Returns a substring of the invoking string, beginning at startIndex and stopping
atstopIndex . This method is required by the CharSequence interface, which is
now implemented by String.
Additional Methods in StringBuffer which was included in Java 5
StringBuffer appendCodePoint(int ch )
Appends a Unicode code point to the end of the invoking object. A reference to
theobject is returned.
in
int codePointAt(int i )
Returns the Unicode code point at the location specified by i.
int codePointBefore(int i )
Returns the Unicode code point at the location that precedes that specified by i.
int codePointCount(int start , int end )
.
Returns the number of code points in the portion of the invoking String that
ud
arebetween start and end– 1.
int indexOf(String str )
Searches the invoking StringBuffer for the first occurrence of str. Returns the index
ofthe match, or –1 if no match is found.
int indexOf(String str , int startIndex )
Searches the invoking StringBuffer for the first occurrence of str, beginning
lo
atstartIndex. Returns the index of the match, or –1 if no match is found.
int lastIndexOf(String str )
Searches the invoking StringBuffer for the last occurrence of str. Returns the index
ofthe match, or –1 if no match is found.
int lastIndexOf(String str , int startIndex )
uc
Searches the invoking StringBuffer for the last occurrence of str, beginning
atstartIndex. Returns the index of the match, or –1 if no match is found.
The append() method concatenates the string representation of any other type of
datato the end of the invoking StringBuffer object. It has several overloaded
versions. Here are a few of its forms:
vt
In Java, both StringBuilder and StringBuffer are classes used to create mutable sequences
of characters. They are designed to provide a more efficient way to concatenate strings
compared to using the String class, which is immutable. Here are the key differences
between StringBuilder and StringBuffer:
Thread-Safety:
StringBuffer: It is thread-safe. All its methods are synchronized, which means it can be
safely used by multiple threads at the same time without causing any issues.
StringBuilder: It is not thread-safe. Its methods are not synchronized, which means it
should not be used by multiple threads simultaneously. However, this makes it faster in a
in
single-threaded environment because there is no overhead of synchronization.
Performance:
.
StringBuilder in a single-threaded environment.
synchronization.
Usage:
ud
StringBuilder: It is faster than StringBuffer because it does not have the overhead of
StringBuffer: Use StringBuffer when you need a mutable sequence of characters that
will be accessed by multiple threads concurrently.
lo
StringBuilder: Use StringBuilder when you need a mutable sequence of characters that
will only be accessed by a single thread, or when thread-safety is not a concern.
Example:
uc
stringBuffer.append("Hello");
stringBuffer.append(" World");
vt
Example:
stringBuilder.append("Hello");
stringBuilder.append(" World");
Use Case: Use StringBuffer in multi-threaded contexts where thread safety is needed.
Use StringBuilder in single-threaded contexts or where thread safety is not an issue and
performance is critical.
. in
ud
lo
uc
vt