@vtucode - in BIS402 Module 2 PDF 2022 Scheme
@vtucode - in BIS402 Module 2 PDF 2022 Scheme
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.
Here, startIndex specifies the index at which the subrange begins, and
numChars specifies the number of characters to use. Here is an
example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
d. To construct a String object that contains the same character sequence as
another String object using this constructor:
String(String strObj)
Here, strObj is a String object.
class MakeString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
Vtucode.in Page 1
String Handling BIS402
String s2 = new
String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
As you can see, s1 and s2 contain the same string.
Vtucode.in Page 2
String Handling BIS402
Note:
String can be constructed by using string
literals.String s1=”Hello World”
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:
int length( )
3. Example
char chars[] = { 'a', 'b', 'c' }; String s = new String(chars);
System.out.println(s.length());// 3
toString()
1. Every class implements toString( ) because it is defined by
Object.However, the default Implementation of toString() is
sufficient.
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.
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
Vtucode.in Page 3
String Handling BIS402
d)
{
width = w; height = h; depth = d;
}
class toStringDemo
{
public static void main(String args[])
{
Box b = new Box(10, 12, 14);
String s = "Box b: " + b;
System.out.println(b);
System.out.println(s);
}
}
The output of this program is shown here:
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.0
Character Extraction
The String class provides a number of ways in which characters can be
extracted from a String object. String object can not be indexed as if they
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
anindividual character via the charAt( ) method.
2. Syntax
char charAt(int where)
Here, where is the index of the character that you want to
obtain.charAt( ) returns the character at the specified location.
3. example,
char ch;
ch = "abc".charAt(1);
assigns the value “b” to
ch.
Java Program
Vtucode.in Page 4
String Handling BIS402
Output:
The character at index 1 is: e
The character at index 7 is: W
The character at index 5 in "Java Programming" is: P
B. getChars( )
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
Vtucode.in Page 5
String Handling BIS402
Output:
The characters copied to destination Array are: World
class getCharsDemo
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
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
Vtucode.in Page 6
String Handling BIS402
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!";
// Get bytes from the string using the platform's default charset
byte[] byteArray = sampleString.getBytes();
// Get bytes from the string using a specified charset (e.g., UTF-8)
try
{
byte[] utf8ByteArray = sampleString.getBytes("UTF-8");
// Print the bytes
System.out.println("The bytes of the string in UTF-8 are:");
for (byte b : utf8ByteArray)
{
System.out.print(b + " ");
}
System.out.println();
}
catch (java.io.UnsupportedEncodingException e)
{
System.out.println("The specified charset is not supported.");
}
}
}
Output:
Vtucode.in Page 7
String Handling BIS402
D. toCharArray( )
If you want to convert all the characters in a String object into a
characterarray, the easiest way is to call toCharArray( ).
String Comparision
String comparison in Java can be performed using several methods, each serving different
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.
Vtucode.in Page 8
String Handling BIS402
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";
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // false
}
}
Output: true
false
b. equalsIgnoreCase( )
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:
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:
public class EqualsIgnoreCaseTrueExample
{
public static void main(String[] args)
{
// Define two strings
String str1 = "HelloWorld";
Vtucode.in Page 9
String Handling BIS402
{
System.out.println("The strings are equal.");
}
else
{
System.out.println("The strings are not equal.");
}
}
}
{
// Define two strings
String str1 = "HelloWorld";
String str2 = "HelloJava";
// Compare the two strings using equalsIgnoreCase()
}
else
{
System.out.println("The strings are not equal.");
}
Vtucode.in Page 10
String Handling BIS402
}
}
Output: The strings are not equal.
C. regionmatches( )
3. For both versions, startIndex specifies the index at which theregion begins
within the invoking String object.
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.
I'll provide two versions: one where regionMatches() returns true and another
where it returns false.
Program 1: regionMatches() Returns true
public class RegionMatchesTrueExample
{
public static void main(String[] args)
{
// Define two strings
String str1 = "HelloWorld";
String str2 = "World";
// Compare regions of the two strings
boolean match = str1.regionMatches(5, str2, 0, 5);
Vtucode.in Page 11
String Handling BIS402
}
else
{
System.out.println("The regions do not match.");
}
}
}
Output: The region matches
Program 2: regionMatches() Returns false
public class RegionMatchesFalseExample
{
public static void main(String[] args)
{
// Define two strings
String str1 = "HelloWorld";
String str2 = "Java";
// Compare regions of the two strings
boolean match = str1.regionMatches(5, str2, 0, 4);
// Print the result
if (match)
{
System.out.println("The regions match.");
}
else
{
Vtucode.in Page 12
String Handling BIS402
{
// Define the string
String str = "HelloWorld";
// Define the prefix
String prefix = "Hello";
Vtucode.in Page 13
String Handling BIS402
}
else
{
System.out.println("The string does not start with the prefix.");
}
}
}
Output: The string starts with the prefix
Program 1: StartsWithTrueExample
Define String: str is "HelloWorld".
Define Prefix: prefix is "Hello".
Check Prefix: str.startsWith(prefix) returns true because str starts with "Hello".
Print Result: The program prints "The string starts with the prefix."
Program2 :
Vtucode.in Page 14
String Handling BIS402
else
{
System.out.println("The string does not start with the prefix.");
}
}
}
Program 2: StartsWithFalseExample
Output: The string does not start with the prefix
Define String: str is "HelloWorld".
Vtucode.in Page 15
String Handling BIS402
Vtucode.in Page 16
String Handling BIS402
}
else
{
System.out.println("The string does not end with the suffix.");
}
}
}
Output: The string does not end with the suffix
Program 2: EndsWithFalseExample
class EqualsNotEqualTo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
equals() Method
The equals() method is a method provided by the Object class, which is overridden by
many classes including String. It compares the content of two objects to determine if
they are logically equal. For strings, equals() compares the actual contents of the
strings, character by character.
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
Vtucode.in Page 17
String Handling BIS402
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.
Note:
equals() compares the contents of two strings.
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.
Here's a simple example demonstrating the use of the compareTo() method:
Program1:
Vtucode.in Page 18
String Handling BIS402
}
else
{
System.out.println(str1 + " and " + str2 + " are equal lexicographically.");
}
}
}
In this example, "apple" is lexicographically less than "banana", so the compareTo()
method returns a negative integer. The program then prints that
Output: "apple" comes before "banana" lexicographically.
Vtucode.in Page 19
String Handling BIS402
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'.
"apple" and "apple" are considered equal lexicographically because they are identical.
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.
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:
Vtucode.in Page 20
String Handling BIS402
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
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
console.log(arr.indexOf(3)); // Output: 2
Java Program
Vtucode.in Page 21
String Handling BIS402
if (array[i] == value)
return i;
}}
Output:
Index of 3 in array: 2
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.
Vtucode.in Page 22
String Handling BIS402
}
// Helper method to find the last index of an element in an array
public static int lastIndexOf(int[] array, int value)
{
for (int i = array.length - 1; i >= 0; i--)
{
if (array[i] == value)
{
return i;
}
}
return -1; // Value not found in the array
}
Output:
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()
Vtucode.in Page 23
String Handling BIS402
method:
Java Program:
}
Output:
Substring from index 7: world!
Substring from index 0 to 5: Hello
Substring from index 7 to 12: world
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
{
Vtucode.in Page 24
String Handling BIS402
}
Output: Concatenated String: Hello, world!
Final Concatenated String: Hello, world! Have a great day!
replace( )
The replace( ) method has two forms.
The first replaces all occurrences of one character in theinvoking string with another
character.
Syntax:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the characterspecified by
replacement. The resulting string is returned.
Example
String s = "Hello".replace('l', 'w');puts the string
“Hewwo” into s.
The second form of replace( ) replaces one character sequence withanother. It has this
general form:
String replace(CharSequence original, CharSequence replacement)
Vtucode.in Page 25
String Handling BIS402
// Use the replace() method to create a new string with the replacements
Output:
trim( )
The trim() method returns a copy of the invoking string from whichany leading and
trailing whitespace has been removed.
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:
Vtucode.in Page 26
String Handling BIS402
Java Program:
public class TrimExample
{
public static void main(String[] args)
{
// Define a string with leading and trailing spaces
String originalString = " Hello, World! ";
Output:
Data Conversion
The valueOf( ) method converts data from its internal format intoa human-readable form.
1. It is a static method that is overloaded within String for all of Java’s built-in types so
that each type can be converted properlyinto a string.
2. valueOf( ) is also overloaded for type Object, so an object of anyclass type you create
can also be used as an argument
Syntax:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])
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.
Vtucode.in Page 27
String Handling BIS402
Syntax:
static String valueOf(char chars[ ], int startIndex, int numChars)
Here, chars is the array that holds the characters, startIndex is theindex into the array of
characters at which the desired substring begins, and numChars specifies the length of the
substring.
public class SimpleValueOfExample
// Integer to String
// Double to String
// Boolean to String
// Char to String
} }
Output:
Vtucode.in Page 28
String Handling BIS402
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 lowercaseequivalent of the
invoking String.
Syntax
String toLowerCase( )
Java Program
Output:
Original string: Hello, World!
Lowercase string: hello, world!
A. toUpperCase()
Vtucode.in Page 29
String Handling BIS402
Syntax
String toUpperCase( )
In Java, the toUpperCase() method is used to convert all characters in a string to uppercase.
// Create a string
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.
Vtucode.in Page 30
String Handling BIS402
stringBuffer.append(" World");
// Replace text
// Delete characters
stringBuffer.delete(11, 12);
In this example:
Vtucode.in Page 31
String Handling BIS402
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
Output: Hello, there World
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.
StringBuffer Constructors
StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
a. The default constructor (the one with no parameters) reserves room for 16
characterswithout reallocation.
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.
Vtucode.in Page 32
String Handling BIS402
Vtucode.in Page 33
String Handling BIS402
}
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.
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.
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)
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
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
{
public static void main(String[] args)
{
// Create a StringBuffer with an initial capacity of 10
StringBuffer stringBuffer = new StringBuffer(10);
Vtucode.in Page 34
String Handling BIS402
setLength( )
To set the length of the buffer with in a StringBufferobject,
Syntax:
Java Program
Vtucode.in Page 35
String Handling BIS402
stringBuffer.setLength(5);
Explanation:
We print the content and length of the StringBuffer after setting the length.
Output:
Initial Length: 13
Vtucode.in Page 36
String Handling BIS402
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
specifiesthe 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
character is at index 0, the second character is at index 1, and so on. Here's how
you can use it:
setChar( ) method
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)
{
Vtucode.in Page 37
String Handling BIS402
// 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!
}
}
Output: Modified string: Hello, Gold!
getChars( ) method
a. To copy a substring of a StringBuffer into an array, use the getChars( )
method.Syntax
Syntax
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.
b. This means that the substring contains the characters from sourceStart
throughsourceEnd–1.
int sourceStart = 0;
int sourceEnd = 5;
Vtucode.in Page 38
String Handling BIS402
int targetStart = 0;
Output:Hello
The method getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) copies characters
from the StringBuffer into the destination character array dst.
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").
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.
Vtucode.in Page 39
String Handling BIS402
a = 42!
insert( )
1. The insert() method inserts one string in to another.
2. It is overloaded to accept values of all the simple types, plus Strings, Objects,
andCharSequences.
3. Like append(),it calls String.valueOf() to obtain the string representation of the
valueit is called with.
4. This string is then inserted into the invoking StringBuffer object.
5. These are a few of its forms:
StringBuffer insert(int index, String str)
class insertDemo
Vtucode.in Page 40
String Handling BIS402
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
Output:
I like Java!
reverse( )
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
called.The following program demonstrates reverse( )
class ReverseDemo
{
public static void main(String args
[]) {
StringBuffer s = new
StringBuffer("abcdef");
System.out.println(s); s
.reverse();
System.out.println(s
); }
}
Output
:
abcdef
fedcba
Vtucode.in Page 41
String Handling BIS402
Here, startIndex specifies the index of the first character to remove, and endIndex
specifiesan 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
theresulting StringBuffer object.
// Demonstrate delete() and deleteCharAt()
class deleteDemo
{
public static void main(String args[])
{
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
Output:
After delete: This a test.
After deleteCharAt: his a
test.
replace( )
Vtucode.in Page 42
String Handling BIS402
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
returned.class replaceDemo
{
public static void main(String args[])
{
}
Here is the output:
After replace: This was a test.
substring( )
1. It has the following two
forms:Syntax
String substring(int startIndex)
String substring(int startIndex, int endIndex)
2. The first form returns the substring that starts at startIndex and runs to the end of
theinvoking StringBuffer object.
3. The second form returns the substring that starts at startIndex and runs through endIndex–
1.
These methods work just like those defined for String that were described earlier.
Difference between StringBuffer and StringBuilder.
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
Vtucode.in Page 43
String Handling BIS402
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 )
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 )
Returns true if the invoking string contains the same string as str. Otherwise,
returnsfalse.
6. boolean contentEquals(StringBuffer str )
Returns true if the invoking string contains the same string as str. Otherwise,
returnsfalse.
7. static String format(String fmtstr , Object ... args )
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
regExp.Otherwise, returns false.
10. int offsetByCodePoints(int start , int num )
Returns the index with the invoking string that is num code points beyond the
startingindex specified by start.
11. String replaceFirst(String regExp , String newStr )
Returns a string in which the first substring that matches the regular
expressionspecified by regExp is replaced by newStr.
12. String replaceAll(String regExp , String newStr )
Returns a string in which all substrings that match the regular expression specified
byregExp are replaced by newStr
13. String[ ] split(String regExp )
Decomposes the invoking string into parts and returns an array that contains
theresult. Each part is delimited by the regular expression passed in regExp.
14. String[ ] split(String regExp , int max )
Decomposes the invoking string into parts and returns an array that contains the
result. Each part is delimited by the regular expression passed in regExp. The
number of pieces is specified by max. If max is negative, then the invoking string is
Vtucode.in Page 44
String Handling BIS402
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.
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
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
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 )
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:
StringBuffer append(String str)
Vtucode.in Page 45
String Handling BIS402
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
single-threaded environment because there is no overhead of synchronization.
Performance:
StringBuilder: It is faster than StringBuffer because it does not have the overhead of
synchronization.
Usage:
StringBuffer: Use StringBuffer when you need a mutable sequence of characters that
will be accessed by multiple threads concurrently.
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:
stringBuffer.append("Hello");
stringBuffer.append(" World");
Example:
stringBuilder.append("Hello");
stringBuilder.append(" World");
Vtucode.in Page 46
String Handling BIS402
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.
Vtucode.in Page 47