Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
116 views

STRING-Module 2 Notes

This document provides notes on Advanced Java for 6th semester Computer Science students at Bangalore Institute of Technology, covering topics such as String handling, StringBuffer, and StringBuilder. It includes explanations of string operations, methods, and comparisons, along with examples of string manipulation in Java. The notes are prepared by Chaithra G V, Assistant Professor, and reference various textbooks for further reading.

Uploaded by

siri219b
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
116 views

STRING-Module 2 Notes

This document provides notes on Advanced Java for 6th semester Computer Science students at Bangalore Institute of Technology, covering topics such as String handling, StringBuffer, and StringBuilder. It includes explanations of string operations, methods, and comparisons, along with examples of string manipulation in Java. The notes are prepared by Chaithra G V, Assistant Professor, and reference various textbooks for further reading.

Uploaded by

siri219b
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

BANGALORE INSTITUTE OF TECHNOLOGY

VV PURAM BANGALORE

ADVANCED JAVA
NOTES FOR 6TH SEMESTER COMPUTER SCIENCE

SUBJECT CODE : BCS613D

PREPARED BY

CHAITHRA G V

ASSISTANT PROFESSOR

TEXT BOOKS

1. Herbert Schildt: Java The Complete Reference, 7th edition, Tata McGraw
Hill, 2007.
2. Uttam k Roy, Adavanced Programming, Oxford University Press.

REFEENCE BOOKS

1. Jim Keogh:J2EE – The Complete Reference,Tata McGraw Hill,2007.


2. Y. Daniel Liang: Introduction to JAVA Programming, 7th Edition,
Pearson Education, 2007.
3. Stehanie Bodoff et al: The J2EE Tutorial, 2nd Edition, Pearson Education,
2004.

1
Prepared By: CHAITHRA G V
MODULE -2

STRING HANDLING

STRING
 The String, StringBuffer, and StringBuilder classes are defined in java.lang by default
available to all programs automatically.
 All are declared final, which means that none of these classes may be subclassed.
 All three implement the CharSequence interface.

Difference between String and String Buffer

Once a String object has been created, we cannot perform any changes to the characters
that comprise that string. If we try to perform any changes, a new Object is
created .Hence, String object is Immutable(non-changeable).

String str = new String(“JAVA”);

str JAVA

str.concate(“DEVELOPER”);

JAVA
str DEVELOPE

System.out.println(str); // JAVADEVELOPER

Once a StringBuffer object is created, we can perform any changes to the characters that
comprises that string. Hence, StringBuffer object is Mutable(changeable).

StringBuffer str = new StringBuffer(“JAVA”);

str.append(“DEVELOPER”);

JAVA
str DEVELOPE

System.out.println(str); // JAVADEVELOPER

2
Prepared By: CHAITHRA G V
The STRING CONSTRUCTOR

1. String s = new String( );

 Creates an empty string using new operator.


 Length of the String s is zero.

2. String s = new String (String str);

For the given string literal an equivalent string object is created.

3. String s = new String(StringBuffer b);

StringBuffer b = new StringBuffer(“JAVA”);


For the given string buffer an equivalent string object is created.

4. String s = new String(char[ ] ch);

char ch[] = { 'a', 'b', 'c' };


For the given character array an equivalent string object is created.

5. String s = new String(byte[ ] b);

byte b[] = { 'a', 'b', 'c' };


For the given byte array an equivalent string object is created.

METHODS OF STRING CLASS

STRING LENGTH

 It defines the number of character it contains.


 Syntax: int length( );
 Ex:

public class Demo1


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

String s1 = new String("hello world");


System.out.println(s1.length()); //11
}
}
STRING OPERATIONS

3
Prepared By: CHAITHRA G V
 String Literals

 Creates an character array using string literals


 Java automatically constructs a String object for every String literal. Hence,
String literals are used to initialize String objects.
 Methods can be called directly on a quoted string.
 Ex :

public class Demo2


{
public static void main(String[] args)
{
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
System.out.println("abc".length());
}
}

 In the above example, for the String literal abc it creates a String Objects s1.
 It calls the length( ) method directly on the string literal "abc".

 String Concatenation

 Java does not allow operators to String objects.


 + Operator which is used to concatenate two Strings, producing a String
object as the result. Hence, allows to chain together a series of + operations.
 Ex:
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);
}
}

 String Concatenation with Other Data Types

int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);

4
Prepared By: CHAITHRA G V
 In the above example, 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.

String s = "four: " + 2 + 2;


System.out.println(s);

The output is four: 22

 In the above example, the value 2 is converted into String type. Hence, it
concatenates 3 string four, 2 and 2.

String s = "four: " + (2 + 2);


System.out.println(s);

The output is "four: 4".

 In the above example, the value (2+2) performs the arithmetic Operations and
then converts the result to String type. Hence, it concatenation 2 strings four and
the result 4.

 String Concatenation with Other Data Types

 When Java converts data into its string representation during concatenation, it
does so by calling one of the overloaded string conversion method valueOf( )
defined by String
 For objects, valueOf( ) calls the toString( ) method on the object.
 Every class by default implements toString( ) because it is defined by Object.
 The general form of toString( ) method is String toString( ).
 Ex:

Without using toString( ) method

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

Student(int rollno,String name,String city)


{
this.rollno = rollno;
this.name = name;
this.city = city;
}

5
Prepared By: CHAITHRA G V
public static void main(String[] args )
{
Student s1 = new Student(111,”sachin”,”Mumbai”);
Student s1 = new Student(222,”rahul”,”bangalore”);

System.out.println(s1);
System.out.println(s2);
}
}

The output of this program is shown here:

Student@1fee6fc
Student@1eed786

using toString( ) method

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

Student(int rollno,String name,String city)


{
this.rollno = rollno;
this.name = name;
this.city = city;
}
public String toString( )
{
return rollno+“ “+name” “+city;
}

public static void main(String[] args )


{
Student s1 = new Student(111,”sachin”,”Mumbai”);
Student s1 = new Student(222,”rahul”,”bangalore”);

System.out.println(s1);
System.out.println(s2);
}
}

The output of this program is shown here:

6
Prepared By: CHAITHRA G V
111 sachin Mumbai
222 rahul Bangalore.

CHARACTER EXTRACTION

 charAt( )

 It is used to extract a single/individual character at a given index from a


String.
 The general form is char charAt(int index)
 The value of index must be nonnegative and specify a location within the
string.
 Ex:
char ch;
ch = "abc".charAt(1); // assigns the value b to ch.

 getChars( )

 It is used to extract a more than one character at a given index from a String.
 The general form is
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
 sourceStart specifies the index of the beginning of the substring
 sourceEnd specifies an index that is one past the end of the desired
substring.
 target contains the array of character from sourceStart to sourceEnd–
1.
 target specifies the index within the target at which the substring will
be copied.
 Ex :

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);
}
}

The output of this program is shown here:

7
Prepared By: CHAITHRA G V
demo

 getBytes( )

 It is used to store characters in array of bytes.


 The general form is byte[ ] getBytes( ).
 Adv :
It is used to export String value into environment that does not support 16
bit Unicode characters.
 toCharArray( )

 It is used to convert all the characters in a String object into a array of


characters.
 The general form is char[ ] toCharArray( ).

STRING COMPARISION

The String class includes a number of methods that compare strings or substrings within
strings.

 equals( )

 It is used to compare two strings for equality using equals( ) method.


 The general form is boolean equals(Object str).
 str is the substring 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.

 equalsIgnoreCase( )

 It is used to compare two strings for equality using equalsIgnoreCase( )


method by ignoring case difference.
 The general form is boolean equalsIgnoreCase(Object str).
 str is the substring 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 not case-sensitive.

// Demonstrate equals() and equalsIgnoreCase().


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

8
Prepared By: CHAITHRA G V
{
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));
}
}
The output from the program is shown

Hello equals Hello -> true


Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

 regionMatches( )

 It is used to compare a specific region inside a string with another specific


region in another string using The regionMatches( ) .
 The general form is
 Case 1 : boolean regionMatches(int startIndex, String str2,int str2StartIndex,
int numChars)
 Case 2 : boolean regionMatches(boolean ignoreCase,int startIndex, String
str2,int str2StartIndex, int numChars)
 In both the general form,
 startIndex specifies the index at which the region begins within the
invoking String object.
 str2 specifies the strings being compared.
 str2StartIndex the index at which the comparision will start within
str2.
 numChars specifies the length of substring being compared.
 In Case 2 , if ignoreCase is true, the case of the
characters is ignored.

 startsWith( )

 It is used to determine whether a given String begins with a specified string.


 The general form is
 Case 1 :boolean startsWith(String str)

9
Prepared By: CHAITHRA G V
 str is the substring being compared with the given String object.
 It returns true if the strings starts with the same characters and same order
in the given string, and false otherwise.
 Ex :

String str = “Foobar”.


Boolean b = startsWith(“Foo”); it returns true

 Case 2 :boolean startsWith(String str, , int startIndex)


 str is the substring being compared with the given String object.
 It returns true if the strings starts with the same characters and same order
in the given string, and false otherwise.
 startIndex specifies the index into the invoking string at which point the
search will begin.
 Ex :

String str = “Foobar”.


Boolean b = startsWith(“Foo”,3); //it returns true

 endsWith( )

 It is used to determine whether a given String ends with a specified string.


 The general form is boolean endsWith(String str)
 str is the substring being compared with the given String object.
 It returns true if the strings emds with the same characters and same order
in the given string, and false otherwise.
 Ex :

String str = “Foobar”.


Boolean b = endsWith(“Foo”); it returns true

 equals( ) versus ==

 The equals( ) method and the == operator perform two different operations.
 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.

//Demonstrate equals( ) versus == operator

class EqualsNotEqualTo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);

10
Prepared By: CHAITHRA G V
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}

The output of this program is shown here:

Hello equals Hello -> true


Hello == Hello -> false

 compareTo( )

 It is used to check whether the string is greater/lesser than the invoking String
Object. In other words, it checks the string comes before or after the invoking
String Object.
 The general form is int compareTo(String str)
 str is the String being compared with the invoking String.

Value Meaning

Less than zero The invoking string is less than str.

Greater than zero The invoking string is greater than str.

Zero The two strings are equal.

//Demonstrate 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];

11
Prepared By: CHAITHRA G V
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}

The output of this program is shown here:


Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to

 compareTo( ) takes into account uppercase and lowercase letters. The word
"Now" came out before all the others because it begins with an uppercase letter,
which means it has a lower value in the ASCII character set.

 compareToIgnoreCase

 It is used to check whether the string is greater/lesser than the invoking String
Object. In other words, it checks the string comes before or after the invoking
String Object.
 It is not case sensitive.
 The general form is int compareToIgnoreCase(String str)
 str is the String being compared with the invoking String.

Value Meaning

Less than zero The invoking string is less than str.

Greater than zero The invoking string is greater than str.

Zero The two strings are equal.


12
Prepared By: CHAITHRA G V
//Demonstrate 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].compareToIgnoreCase(arr[j]) < 0)
{
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}

 "Now" will no longer be first.

SEARCHING STRING

It includes two methods to search a string for a specified character or


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

 indexOf( )

 It is used to search for the first occurrence of a character or


substring.
 The general form is

13
Prepared By: CHAITHRA G V
Case 1: int indexOf(int ch)
Case 2: int indexOf(String str)
Case 3: int indexOf(int ch, int startIndex)
Case 4: int indexOf(String str, int startIndex)

ch is the character to search for the first or last occurrence of a substring.


str specify a starting point for the search.
startIndex specifies the index at which point the search begins.

 lastIndexOf( )

 It is used to search for the last occurrence of a character or


substring.
 The general form is
Case 1: int lastIndexOf(int ch)
Case 2: int lastIndexOf(String str)
Case 3: int lastIndexOf(int ch, int startIndex)
Case 4: int lastIndexOf(String str, int startIndex)

ch is the character to search for the first or last occurrence of a substring.


str specify a starting point for the search.
startIndex specifies the index at which point the search begins.

// 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));

14
Prepared By: CHAITHRA G V
System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the",
60));
}
}

The output of this program is shown here:

Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55

MODIFYING A STRING

 substring( )

 It is used to extract substring using substring( ).


 The general form is
Case 1: String substring(int startIndex)
 startIndex specifies the index at which the substring will begin.
 It returns a copy of the substring that begins at startIndex and runs to
the end of the invoking string.

Case 2: String substring(int startIndex, int endIndex)


 startIndex specifies the beginning index.
 endIndex specifies the stopping point.
 It returns all the characters from the start index, up to, but not
 including, the end index.

// Demonstrate Substring replacement

class StringReplace
{
public static void main(String args[])
{
String org = "This is a test. This is, too.";
String search = "is";
String sub = "was";
String result = "";
int i;

15
Prepared By: CHAITHRA G V
do
{
System.out.println(org);
i = org.indexOf(search);
if(i != -1)
{
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}

The output from this program is shown here:

This is a test. This is, too.


Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

 substring( )

 It is used to extract substring using substring( ).


 The general form is String concat(String str)
It creates a new object that contains the invoking string with the contents
of str appended to the end.
 concat( ) performs the same function as +.
 Ex :

String s1 = "one";
String s2 = s1.concat("two"); // puts the string "onetwo" into s2.

 replace( )

 It is used to extract substring using substring( ).


 The general form is
Case 1: String replace(char original, char replacement)
original specifies the character to be replaced.
replacement specifies the character replaced.

Case 2: String replace(char original, char replacement)


It replaces one character sequence with another.
 Ex :

16
Prepared By: CHAITHRA G V
String s = “hello”;
String str = s.replace(e,E);

 trim( )

 It is used to copy of the invoking string from which whitespace has been
removed.
 The general form is String trim( ).

Demonstrate trim() to process commands.


import java.io.*;
class UseTrim
{
public static void main(String args[]) throws IOException
{
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"));
}
}

CHANGING THE CASES OF CHARACTER WITHIN A STRING

 toLowerCase( )
17
Prepared By: CHAITHRA G V
 It is used to converts all the characters in a string from uppercase to lowercase.
 The general form is String toLowerCase( )

 toUpperCase( )

 It is used to converts all the characters in a string from lowercase to uppercase.


 The general form is String toUpperCase( )
 Ex :

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);
}
}
The output produced by the program is shown here:

Original: This is a test.


Uppercase: THIS IS A TEST.
Lowercase: this is a test.

JOINING STRINGS

 It is used to concatenate two or more strings, separating each string with a delimiter, such
as a space or a comma.
 The general form is static String join(CharSequence delim, CharSequence . . . strs)
 specifies the delimiter used to separate the character sequences specified by strs.
 Ex :

// 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);

18
Prepared By: CHAITHRA G V
result = String.join(", ", "John", "ID#: 569","E-mail: John@HerbSchildt.com");
System.out.println(result);
}
}

The output is shown here:


Alpha Beta Gamma
John, ID#: 569, E-mail: John@HerbSchildt.com

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

ADDITIONAL STRINGS METHODS

METHOD MEANING

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, Returns the number of code points


int end) in the portion of the invoking
String that are between start and
end–1.

boolean Returns true if the invoking object


contains(CharSequence str) contains the

string specified by str. Returns


false otherwise.

boolean Returns true if the invoking string


contentEquals(CharSequence contains the same string as str.
str) Otherwise, returns false.

boolean Returns true if the invoking string


contentEquals(StringBuffer contains the same string as str.

19
Prepared By: CHAITHRA G V
str) Otherwise, returns false.

static String format(String Returns a string formatted as


fmtstr,Object ... args) specified by fmtstr. (See Chapter 19
for details on formatting.)

static String format(Locale Returns a string formatted as


loc,String fmtstr,Object ... specified by fmtstr.Formatting is
args) governed by the locale specified by
loc.(See Chapter 19 for details on
formatting.)

boolean isEmpty( ) Returns true if the invoking string


contains no

characters and has a length of zero.

boolean matches(string Returns true if the invoking string


regExp) matches the regular expression
passed in regExp. Otherwise,
returns false.

int offsetByCodePoints(int Returns the index within the


start, int num) invoking string that is num code
points beyond the starting index
specified by start.

String replaceFirst(String Returns a string in which the first


regExp, substring that matches the regular
expression specified by regExp is
String newStr)
replaced by newStr.

String replaceAll(String regExp, Returns a string in which all substrings that


match the regular expression specified by
String newStr) regExp are replaced by newStr.

String[ ] split(String regExp) Decomposes the invoking string


into parts and

returns an array that contains the

20
Prepared By: CHAITHRA G V
result. Each part is delimited by the
regular expression passed in
regExp.

String[ ] split(String regExp, Decomposes the invoking string


int max) 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 fully decomposed.


Otherwise, if max contains a
nonzero value, the last entry in the
returned array contains the
remainder of the invoking string. If
max is zero, the invoking string is
fully decomposed, but no trailing
empty strings will be included.

CharSequence Returns a substring of the invoking


subSequence(int string, beginning at startIndex and
startIndex,int stopIndex) stopping at stopIndex. This method
is required by the CharSequence
interface, which is implemented by
String.

STRINGBUFFER
 StringBuffer represents fixed-length, immutable character
sequences and modifiable string.
 It represents growable and writable.
 It may have characters and substrings inserted in the middle or
appended to the end.

STRINGBUFFER CONSTRUCTOR

1. StringBuffer s = new StringBuffer( );

21
Prepared By: CHAITHRA G V
 Creates an empty string using new operator with default capacity 16.
 Once its reaches its maximum capacity then a new StringBuffer object will be
created with new_capacity = (current_capacity+1)*2.
 The performance decreases with the default capacity. To overcome the above
problem, StringBuffer object with intial capacity was created.

2. String s = new String(int initial_size);

 If we know the initial capacity in advance, then StringBuffer object with intial
capacity is used. Hence the performance of the system increases.

3. StringBuffer s = new StringBuffer (String str);

 For the given string literal str an equivalent stringBuffer object is created.
 The capacity of StringBuffer s is length of str + capacity of s.
 Ex :

StringBuffer b = new StringBuffer(“JAVA”);


Length of b = 16+4 = 20.

4. StringBuffer s = new StringBuffer (CharSequence chars);

 For the given character sequence chars an equivalent stringBuffer object is


created.
 It reserves room for 16 more characters.

METHODS OF STRINGBUFFER CLASS

 length( )

 It is used to find the current length of StringBuffer.


 The general form is int length( ).

 capacity( )
 It is used to find the current capacity of StringBuffer.
 The general form is int capacity( ).

Demonstrate StringBuffer length vs. capacity.

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

22
Prepared By: CHAITHRA G V
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
The output of this program is:
buffer = Hello
length = 5
capacity = 21
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( )
 It is used to to preallocate room for a certain number of characters after a
StringBuffer has been constructed.
 The general form is void ensureCapacity(int minCapacity).
 minCapacity specifies the minimum size of the buffer.

 setLength( )

 It is used to set the length of the string within a StringBuffer object.


 The general form is void setLength(int len)
len specifies the length of the string and value must be non negative.
 When the String size increases/decreases null characters are added to the end.
 When the String size decreases characters stored beyond the new length will be
lost.

 charAt( )

 It is used to extract a single/individual character at a given index from a String


using StringBuffer.
 The general form is char charAt(int index)
 The value of index must be nonnegative and specify a location within the
string.
 Ex:
char ch;
ch = "abc".charAt(1); // assigns the value b to ch
 setCharAt( )

 It is used to set the value of a character within a StringBuffer .


 The general form is char setCharAt(int index)

23
Prepared By: CHAITHRA G V
 The value of index must be nonnegative and specify a location within the
string.
// 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));
}
}
The output generated by this program:

buffer before = Hello


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

 getChars( )

 It is used to copy a substring of a StringBuffer into an array.


 The general form is
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
 sourceStart specifies the index of the beginning of the substring
 sourceEnd specifies an index that is one past the end of the desired
substring.
 target contains the array of character from sourceStart to sourceEnd–
1.
 target specifies the index within the target at which the substring will
be copied.
 append( )

 It is used to concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object.
 The general form is
Case 1: StringBuffer append(String str)
Case 2: StringBuffer append(int num)
Case 3: StringBuffer append(Object obj)
 The string representation of each parameter is obtained, often by calling
String.valueOf( ).

24
Prepared By: CHAITHRA G V
// 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);
}
}
The output of this example is shown here:
a = 42!

 insert( )

 It is used to inserts one string into another


 The general form is
Case 1: StringBuffer insert(int index, String str)
Case 2: StringBuffer insert(int index, char ch)
Case 3: StringBuffer insert(int index, Object o)
index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.

// Demonstrate insert().

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

sb.insert(2, "like ");


System.out.println(sb);
}
}
The output of this example is shown here:
I like Java!

 reverse( )

 It is used to characters within a StringBuffer object.


 The general form is StringBuffer reverse( )

25
Prepared By: CHAITHRA G V
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);
}
}

The output produced by the program:


abcdef
fedcba

 delete( )

 It is used delete characters within a StringBuffer


 The general form is StringBuffer delete(int startIndex, int endIndex)
startIndex specifies the index of the first character to remove.
endIndex specifies an index one past the last character to remove.
 The substring deleted runs from startIndex to endIndex–1.

 deleteCharAt( )

 It is used delete characters at the given index within a StringBuffer object.


 The general form is StringBuffer delete(int startIndex, int endIndex)
startIndex specifies the index of the first character to remove.
endIndex specifies an index one past the last character to remove.
 The substring deleted runs from startIndex to endIndex–1.

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

26
Prepared By: CHAITHRA G V
}

The following output is produced:

After delete: This a test.


After deleteCharAt: his a test.

 replace( )

 It is used to replace one set of characters with another set inside a StringBuffer
object
 The general form is replace(int startIndex, int endIndex, String str)
startIndex specifies the index of the first character.
endIndex specifies an index one past the last character.
 The substring at startIndex through endIndex–1 is replaced.
 Ex :

// 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);
}
}
The output:
After replace: This was a test.

 substring( )

 It is used to extract of a StringBuffer .


 The general form is
Case1: String substring(int startIndex)
 It returns the substring from startIndex and runs to the end of the
invoking StringBuffer object.
 startIndex specifies the index of the first character.

Case2: String substring(int startIndex,int endIndex)


 It returns the substring that starts at startIndex and runs through
endIndex–1.
 endIndex specifies an index one past the last character.

ADDITIONAL STRINGBUFFER METHODS


27
Prepared By: CHAITHRA G V
METHOD MEANING

StringBuffer appendCodePoint(int Appends a Unicode code point to the end of


ch) the invoking object. A reference to the object
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, Returns the number of code points


int end) in the portion of the invoking String
that are between start and end–1.

int indexOf(String str) Searches the invoking StringBuffer for the


first occurrence of str. Returns the index of
the 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 at
startIndex. 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, beginning at
startIndex. Returns the index of the match, or
–1 if no match is found.

int lastIndexOf(String str, int Searches the invoking StringBuffer for the
startIndex) last occurrence of str, beginning at
startIndex. Returns the index of the match, or
. –1 if no match is found.

int offsetByCodePoints(int Returns the index within the


start, int num) invoking string that is num code
points beyond the starting index

28
Prepared By: CHAITHRA G V
specified by start.

CharSequence Returns a substring of the invoking


subSequence(int string, beginning at startIndex and
startIndex,int stopIndex) stopping at stopIndex. This method
is required by the CharSequence
interface, which is implemented by
String.

void trimToSize( ) Requests that the size of the character buffer


for the invoking object be reduced to better
fit the current contents.

29
Prepared By: CHAITHRA G V

You might also like