0% found this document useful (0 votes)
1 views27 pages

Updated Module 2

Module 2 covers string handling in Java, including string constructors, length, special operations, and comparisons. It explains the difference between mutable and immutable string objects, provides examples of string manipulation, and discusses methods for searching, modifying, and converting strings. Additionally, it highlights important methods like equals(), compareTo(), and substring() for effective string management.

Uploaded by

4al22cs128
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)
1 views27 pages

Updated Module 2

Module 2 covers string handling in Java, including string constructors, length, special operations, and comparisons. It explains the difference between mutable and immutable string objects, provides examples of string manipulation, and discusses methods for searching, modifying, and converting strings. Additionally, it highlights important methods like equals(), compareTo(), and substring() for effective string management.

Uploaded by

4al22cs128
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
You are on page 1/ 27

Module 2

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

Text Book 1: Ch 17 ( starts from page 645)

Unlike some other languages that implement strings as character arrays, Java implements strings as
objects of type String.

Types of string objects : Mutable and Immutable objects


The object which can be modified is called mutable objects
The object which can not be modified and if it is modified, a new object will be generated , original
value will be restored is called immutable object

Example program for StringBuilder and String

package Strings;

public class object_types {

public object_types() {
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {


String s="~";

//Immutable string example in Java


System.out.println("using String object which is immutable");
System.out.println(s.repeat(40));
String text = new String("Hello");
System.out.println("Original: " + text + ", Hash: " + System.identityHashCode(text));

//Modifying the string


text+=" World";
System.out.println("Modified: " + text + ", Hash: " + System.identityHashCode(text));
System.out.println(s.repeat(40));

System.out.println("using StringBuilder object which is mutable");


System.out.println(s.repeat(40));
//Mutable string example in Java
StringBuilder text1 = new StringBuilder("Hello");
System.out.println("Original: " + text1 + ", Hash: " + System.identityHashCode(text1));

//Modifying the string


text1.append(" World");
System.out.println("Modified: " + text1 + ", Hash: " +
System.identityHashCode(text1));
System.out.println(s.repeat(40));
//What happened:
//- The same object was modified
//- The memory address remains the same
//- No new object was created
}

o/p

using String object which is immutable


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Original: Hello, Hash: 245565335
Modified: Hello World, Hash: 2121744517
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
using StringBuilder object which is mutable
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Original: Hello, Hash: 1066376662
Modified: Hello World, Hash: 1066376662
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The String Constructors

The String class supports several constructors. To create an empty String, call the default constructor.
For example,

String s = new String();

will create an instance of String with no characters in it.

Frequently, you will want to create strings that have initial values. The String class provides a variety of
constructors to handle this. To create a String initialized by an array of characters, use the constructor
shown here:

char chars={‘a’,’b’,’c’};
String s= new String(chars);

This constructor initializes s with the string "abc".

String(char chars[ ])
Here is an example:
This constructor initializes s with the string "abc".
// Construct one String from another.
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);
}
}

o/p

Java
Java

// Construct string from subset of char array.


class SubStringCons {
public static void main(String[] args) {
byte[] ascii = {65, 66, 67, 68, 69, 70};

String s1 = new String(ascii);


System.out.println(s1);

String s2 = new String(ascii, 2, 3);


System.out.println(s2);
}
}

o/p

ABCDEF
CDE

String Length
The length of a string is the number of characters that it contains. To obtain this
value, call the length( ) method, shown here:
int length( )
The following fragment prints 3, since there are three characters in the string s:
Special String Operations

String Literals

the following code fragment creates two equivalent strings:

As expected, the following code prints "3".

System.out.println(“abc”.length());

String Concatenation

In general, Java does not allow operators to be applied to String objects. The one exception to this rule
is the + operator, which concatenates two strings, producing a String object as the result. This allows
you to chain together a series of + operations.

// Using concatenation to prevent long lines.


class ConCat {
public static void main(String[] args) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +
"prevents this.";
System.out.println(longStr);
}
}

o/p

This could have been a very long line that would have wrapped around. But string concatenation
prevents this.
String Concatenation with Other Data Types

You can concatenate strings with other types of data. For example, consider this slightly different
version of the earlier example:

In this case, age is an int rather than another String, but the output produced is the same as before. This
is because the int value in age is automatically converted into its string representation within a String
object. This string is then concatenated as before. The compiler will convert an operand to its string
equivalent whenever the other operand of the + is an instance of String.

Be careful when you mix other types of operations with string concatenation expressions, however. You
might get surprising results. Consider the following:
String Conversion and toString( )

If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the String representation of the object.
If you print any object, Java compiler internally invokes the toString() method on the object. So overriding
the toString() method, returns the desired output, it can be the state of an object etc. depending on your
implementation.

class Student{
int rollno;
String name;
String city;

Student(int rollno, String name, String city){


this.rollno=rollno;
this.name=name;
this.city=city;
}
//overriding the toString() method
public String toString(){
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()


System.out.println(s2);//compiler writes here s2.toString()
}
}

o/p

101 Raj lucknow


102 Vijay ghaziabad

Character Extraction

charAt( )

To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where
must be nonnegative and specify a location within the string. charAt( ) returns the
character at the specified location. For example,

assigns the value b to ch.

getBytes()

getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of
bytes.

public class StringGetBytesExample


{
public static void main(String args[]){
String s1="ABCDEFG";
byte[] barr=s1.getBytes();
for(int i=0;i<barr.length;i++){
System.out.print(barr[i])+" ");
}
}

o/p

65 66 67 68 69 70 71
toCharArray()

In Java, the toCharArray() method of the String class converts the given string into a character array.

// Java program to print individual


// characters of a string
// Using toCharArray()
public class ToCharArray1 {

public static void main(String[] args) {

// Define a string
String s = "AIET";

// Convert the string to a character array


char[] ca = s.toCharArray();

for (char ch : ca) {


System.out.print(ch+" ");
}
}
}

o/p

AIET

Explanation: In the above example, the toCharArray() method breaks the string "AIET" into individual
characters for processing. Then a for-each loop iterates through the array and prints each character

String Comparison

The String class includes a number of methods that compare strings or substrings
within strings. Several are examined here.

equals( ) and equalsIgnoreCase( )

// Demonstrate equals() and equalsIgnoreCase().


class equalsDemo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}

o/p
regionMatches( )

The regionMatches( ) method compares a specific region inside a string with another specific region in
another string. There is an overloaded form that allows you to ignore case in such comparisons

In Java, regionMatches() method of the String class compares parts (regions) of two strings to see if
they match. It offers both case-sensitive and case-insensitive comparison options. This method is
commonly used in string matching and validation tasks

// Java Program to demonstrate regionMatches() method


public class RegionMatches {

public static void main(String[] args) {

// Create two string objects


String s1 = "Hello, welcome to Java!";
String s2 = "welcome";

// Compare substring of s1 and s2


boolean res = s1.regionMatches(7, s2, 0, 7);

System.out.println("" + res);
}
}

o/p

true

startsWith( ) and endsWith( )

String defines two methods that are, more or less, specialized forms of regionMatches( ). The
startsWith( ) method determines whether a given String begins with a specified string. Conversely,
endsWith( ) determines whether the String in question ends with a specified string.

In Java, the startsWith() and endsWith() methods of the String class are used to check whether a string
begins or ends with a specific prefix or suffix, respectively.

Example:

This example demonstrates the usage of the startsWith() and endsWith() methods in Java.

// Java Program to demonstrate


// startsWith() and endsWith() methods
// of the String class
public class Start_End_With{

public static void main(String[] args) {

String s = "Java Programming";

// Check if string starts with "Java"


System.out.println("Starts with 'Java': " + s.startsWith("Java"));

// Check if string ends with "Programming"


System.out.println("Ends with 'Programming': " + s.endsWith("Programming"));
}

o/p

Starts with 'Java': true


Ends with 'Programming': true

equals( ) Versus ==

It is important to understand that the equals( ) method and the == operator perform two different
operations. As just explained, 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. The
following program shows how two different String objects can contain the same characters, but
references to these objects will not compare as equal

// equals() vs ==
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));
}
}

o/p
compareTo( )

Often, it is not enough to simply know whether two strings are identical. For sorting applications, you
need to know which is less than, equal to, or greater than the next. 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 method compareTo( ) serves this purpose. It is specified by the Comparable<T>
interface, which String implements. It has this general form:
int compareTo(String str)
Here, str is the String being compared with the invoking String. The result of the comparison is
returned and is interpreted as shown here:

// A bubble sort for Strings.


class SortString {
static String[] arr = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};

public static void main(String[] args) {


for (int j = 0; j < arr.length; j++) {
for (int i = j + 1; i < arr.length; i++) {
if (arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}

o/p

Searching Strings

The String class provides two methods that allow you to search a string for a specified character or
substring:

• indexOf( ) Searches for the first occurrence of a character or substring.


• lastIndexOf( ) Searches for the last occurrence of a character or substring.

// Demonstrate indexOf() and lastIndexOf().


class indexOfDemo {
public static void main(String[] args) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";

System.out.println(s);
System.out.println("indexOf(t) = " +
s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +
s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +
s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +
s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +
s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +
s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +
s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +
s.lastIndexOf("the", 60));
}
}
o/p

Modifying a String

Because String objects are immutable, whenever you want to modify a String, you must either copy it
into a StringBuffer or StringBuilder.

substring( )
You can extract a substring using substring( ). It has two forms. The first is

String substring(int startIndex)

Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the
substring that begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and ending index of the
substring:

String substring(int startIndex, int endIndex)

Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string
returned contains all the characters from the beginning index, up to, but not including, the ending
index.

In Java, substring() method of String class returns a substring from the given string. This method is
most useful when you deal with text manipulation, parsing, or data extraction.

This method either take 1 parameter or 2 parameters i.e. start and end value as arguments.
In case, if the end parameter is not specified then the substring will end at the end of the string.
Syntax:

public String substring(int begIndex);


or
public String substring(int begIndex, int endIndex)

Example 1: Here, we are using the substring(int begIndex) method to extract a substring from the given
string starting at index 6 and ending at the end of the string. The substring begins at index 7, and since
no endIndex is provided, it continues to the end of the string. begIndex is inclusive.

// Java program to show the use of


// substring(int begIndex)

public class Geeks {

public static void main(String[] args)


{

String str = "GeeksforGeeks";

// Extracting substring starting from index 7


String substr = str.substring(7);

// printing the substring


System.out.println("Substring: " + substr);
}
}

Output
Substring: rGeeks

Example 2: Here, we will use the String substring(begIndex, endIndex) method. This method will
return the substring that begins with the character at the specified index and ends at endIndex – 1

begIndex – the begin index, inclusive.


endIndex – the end index, exclusive.

// Java program to show the use of


// substring(int begIndex, int endIndex)

public class Geeks {

public static void main(String[] args)


{

String str = "Welcome to GeeksforGeeks";

// Extract substring from index 0(inclusive)


// to 12 (exclusive)
String substr = str.substring(0, 12);

// printing the substring


System.out.println("Substring: " + substr);
}
}

Substring: Welcome to G

concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the
contents of str appended to the end. concat( ) performs the same function as +. For
example,

puts the string "onetwo" into s2. It generates the same result as the following
sequence:

replace( )

The replace( ) method has two forms. The first replaces all occurrences of one
character in the invoking string with another character. It has the following general
form:

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. For example,

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)

trim( )
The trim( ) method returns a copy of the invoking string from which any leading andtrailing whitespace
has been removed. It has this general form:
String trim( )
Here is an example:

This puts the string "Hello World" into s.

The trim( ) method is quite useful when you process user commands. For example, the following
program prompts the user for the name of a state and then displays that state’s capital. It uses trim( ) to
remove any leading or trailing whitespace that may have inadvertently been entered by the user.

// Using trim() to process commands.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class UseTrim {
public static void main(String[] args)
throws IOException {
// create a BufferedReader using System.in
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));

String str;
System.out.println("Enter 'stop' to quit.");
System.out.println("Enter State: ");
do {
str = br.readLine();
str = str.trim(); // remove whitespace

if (str.equals("Illinois"))
System.out.println("Capital is Springfield.");
else if (str.equals("Missouri"))
System.out.println("Capital is Jefferson City.");
else if (str.equals("California"))
System.out.println("Capital is Sacramento.");
else if (str.equals("Washington"))
System.out.println("Capital is Olympia.");
// ...
} while (!str.equals("stop"));
}
}

o/p

Enter 'stop' to quit.


Enter State:
Missouri
Capital is Jefferson City.
Washington
Capital is Olympia.

stop

Data Conversion Using valueOf( ) (Page no 665)

The valueOf( ) method converts data from its internal format into a human-readable
form. 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 properly into a string. valueOf( ) is also
overloaded for type Object, so an object of any class type you create can also be
used as an argument. (Recall that Object is a superclass for all classes.) Here are a
few of its forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ])

The String.valueOf() method in Java is a multipurpose static method. Its major function lies in the
conversion of types of data, such as primitive types and objects, into strings. The technique provides an
efficient and convenient way to construct string objects from different sources.
Java's valueOf() method is overloaded with numerous forms, each of that is designed to handle specific
data types. It can handle converting boolean, char, char array, double, float, int, long, and Object types
into their respective string representations.

With the help of valueOf(), developers can get back string representations of variables and objects
without the need to concatenate or modify strings directly. It simplifies the code and enhances
readability by offering a cleaner option instead of string conversion with the hands.package Strings;

public class StringValueOfExample {


public static void main(String[] args) {
// Primitive types
boolean myBoolean = true; // Example boolean value
char myChar = 'A'; // Example char value
int myInt = 42; // Example int value
long myLong = 123456789L; // Example long value
float myFloat = 123.45f; // Example float value
double myDouble = 987.654; // Example double value
// Objects
Object myObject = new Object(); // Example Object
Integer myIntegerObject = 123; // Example Integer object
Double myDoubleObject = 456.789; // Example Double object
// Using valueOf() to convert various types to String
String booleanString = String.valueOf(myBoolean); // Convert boolean to String
String charString = String.valueOf(myChar); // Convert char to String
String intString = String.valueOf(myInt); // Convert int to String
String longString = String.valueOf(myLong); // Convert long to String
String floatString = String.valueOf(myFloat); // Convert float to String
String doubleString = String.valueOf(myDouble); // Convert double to String
String integerObjectString = String.valueOf(myIntegerObject); // Convert Integer object to String
String doubleObjectString = String.valueOf(myDoubleObject); // Convert Double object to String
// Displaying the results
System.out.println("Boolean: " + booleanString);
System.out.println("Char: " + charString);
System.out.println("Int: " + intString);
System.out.println("Long: " + longString);
System.out.println("Float: " + floatString);
System.out.println("Double: " + doubleString);
System.out.println("Integer Object: " + integerObjectString);
System.out.println("Double Object: " + doubleObjectString);
}
}
o/p
Boolean: true
Char: A
Int: 42
Long: 123456789
Float: 123.45
Double: 987.654
Integer Object: 123
Double Object: 456.789

Changing the Case of Characters Within a String

The method toLowerCase( ) converts all the characters in a string from uppercase to lowercase. The
toUpperCase( ) method converts all the characters in a string from lowercase to uppercase.

Nonalphabetical characters, such as digits, are unaffected.


Here are the simplest forms of these methods:

String toLowerCase( )

String toUpperCase( )

Both methods return a String object that contains the uppercase or lowercase equivalent of the invoking
String. The default locale governs the conversion in both cases.
Here is an example that uses toLowerCase( ) and toUpperCase( ):

class ChangeCase {
public static void main(String[] args) {
String s = "This is a test.";

System.out.println("Original: " + s);

String upper = s.toUpperCase();


String lower = s.toLowerCase();

System.out.println("Uppercase: " + upper);


System.out.println("Lowercase: " + lower);
}
}

o/p
String joining

It is used to concatenate two or more strings, separating each string with a delimiter, such as a space or
a comma. It has two forms. Its first is shown here:
static String join(CharSequence delim, CharSequence ... strs)
Here, delim specifies the delimiter used to separate the character sequences specified by strs. Because
String implements the CharSequence interface, strs can be a list ofstrings. (See Chapter 18 for
information on CharSequence.) The following program demonstrates this version of join( ):

// Demonstrate the join() method defined by String.


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

String result = String.join(" ", "Alpha", "Beta", "Gamma");


System.out.println(result);

result = String.join(", ", "John", "ID#: 569",


"E-mail: [email protected]");
System.out.println(result);
}
}

o/p
Alpha Beta Gamma

John, ID#: 569, E-mail: [email protected]

In the first call to join( ), a space is inserted between each string. In the second call, the delimiter is a
comma followed by a space. This illustrates that the delimiter need not be just a single character.

StringBuffer

StringBuffer supports a modifiable string. As you know, String represents fixed- length, immutable
character sequences. In contrast, StringBuffer represents growable and writable character sequences.

StringBuffer may have characters and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such additions and often has more characters
preallocated 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)
length( ) and capacity( )

The current length of a StringBuffer can be found via the length( ) method, while the total allocated
capacity can be found through the capacity( ) method. They have the following general forms:

int length( )
int capacity( )

Here is an example:

// StringBuffer length vs. capacity.


class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

System.out.println("buffer = " + sb);


System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}

o/p

Since sb is initialized with the string "Hello" when it is created, its length is 5. Its capacity is 21
because room for 16 additional characters is automatically added.

ensureCapacity( )
If you want to preallocate room for a certain number of characters after a StringBuffer has been
constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in
advance that you will be appending a largenumber of small strings to a StringBuffer. ensureCapacity( )
has this general form:
void ensureCapacity(int minCapacity)

Here, minCapacity specifies the minimum size of the buffer. (A buffer larger than minCapacity may be
allocated for reasons of efficiency.)

setLength( )

To set the length of the string within a StringBuffer object, use setLength( ). Its general form is shown
here:
void setLength(int len)

Here, len specifies the length of the string. This value must be nonnegative.
When you increase the size of the string, null characters are added to the end. If you call setLength( )
with a value less than the current value returned by length( ), then the characters stored beyond the new
length will be lost. The setCharAtDemo sample program in the following section uses setLength( ) to
shorten a StringBuffer.

// Demonstrate charAt() and setCharAt().


class setCharAtDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}

o/p

buffer before = Hello


charAt(1) before = e
buffer after = Hi
charAt(1) after = I

getChars( )

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart);

GetChars( )

If you need to extract more than one character at a time, you can use the getChars( ) method

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);
}
}
o/p
demo

append( )

The append( ) method concatenates the string representation of any other type of data to the end of the
invoking StringBuffer object. It has several overloaded versions. Here are a few of its forms:

StringBuffer append(String str)


StringBuffer append(int num)
StringBuffer append(Object obj)

The string representation of each parameter is obtained, often by calling String.valueOf( ). The result is
appended to the current StringBuffer object. The buffer itself is returned by each version of append( ).
This allows subsequent calls to be chained together, as shown in the following example:

// Demonstrate append().
class appendDemo {
public static void main(String[] args) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);

s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}

o/p
a=42!

insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the primitive
types, plus String S , Object S , and CharSequence S . Like append(), it obtains the string representation
of the value it is called with. This string is then inserted into the invoking StringBuffer object. These
are a few of its forms:

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
Here, index specifies the index at which point the string will be inserted into the invoking StringBuffer
object.
The following sample program inserts "like" between "I" and "Java":

// Demonstrate insert().
class insertDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("I Java!");

sb.insert(2, "like ");


System.out.println(sb);
}
}

o/p

I like Java!

reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
This method returns the reverse of the object on which it was called. The following program
demonstrates reverse( ):

// Using reverse() to reverse a StringBuffer.


class ReverseDemo {
public static void main(String[] args) {
StringBuffer s = new StringBuffer("abcdef");

System.out.println(s);
s.reverse();
System.out.println(s);
}
}

o/p
abcdef
fedcba

delete( ) and deleteCharAt( )


You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ).
These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of characters from the invoking object. 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
StringBuffer object is returned. The deleteCharAt( ) method deletes the character at the index specified
by loc. It returns the resulting StringBuffer object

// Demonstrate delete() and deleteCharAt()


class deleteDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("This is a test.");

sb.delete(4, 7);
System.out.println("After delete: " + sb);

sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}

o/p

After delete: This a test.


After deleteCharAt: his a test.

replace( )
You can replace one set of characters with another set inside a StringBuffer object by calling replace( ).
Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)

The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at
startIndex through endIndex–1 is replaced. The replacement string is passed in str. The resulting
StringBuffer object is returned.
The following program demonstrates replace( ):

// Demonstrate replace()
class replaceDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("This is a test.");

sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
After replace: This was a test.

Substring( )

You can obtain a portion of a StringBuffer by calling substring( ). It has the


following two forms:

String substring(int startIndex)


String substring(int startIndex, int endIndex)

The first form returns the substring that starts at startIndex and runs to the end of the invoking
StringBuffer object. 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

StringBuilder

StringBuilder is similar to StringBuffer except for one important difference: it is not synchronized,
which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However,
in cases in which a mutable string will be accessed by multiple threads, and no external
synchronization is employed, you must use StringBuffer rather than StringBuilder.

Feature String StringBuilder StringBuffer


Introduction Introduced in JDK 1.0 Introduced in JDK 1.5 Introduced in JDK 1.0
Mutability Immutable Mutable Mutable
Thread Safety Not Thread Safe Not Thread Safe Thread Safe
Memory
High Efficient Less Efficient
Efficiency
Low(Due to
Performance High(No-Synchronization) High(No-Synchronization)
Synchronization)
This is used when we want This is used when Thread This is used when Thread
Usage
immutability. safety is not required. safety is required.

No. StringBuffer StringBuilder


StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread
1) means two threads can't call the methods of safe. It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
StringBuffer is less efficient than
2) StringBuilder is more efficient than StringBuffer.
StringBuilder.
Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of StringBuffer and StringBuilder classes.

//Java Program to demonstrate the performance of StringBuffer and StringBuilder classes.


public class PerformanceTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) +
"ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
sb2.append("Tpoint");
}
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) +
"ms");
}
}
o/p
Time taken by StringBuffer: 4ms
Time taken by StringBuilder: 1ms

You might also like