Lab 09 Java - 2k22
Lab 09 Java - 2k22
Lab Manual - 9
OOP
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java
Laboratory 09:
Statement Purpose:
After this lab, students will be able to:
i. Use different methods of StringBuffer class in Java.
ii. Use String Tokenizer class in Java.
StringBuffer will automatically grow to make room for such additions and often has more characters
pre-allocated than are needed, to allow room for growth.
StringBuffer Constructors
StringBuffer defines theses three constructors:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
The default constructor (the one with no parameters) reserves room for 16 characters.
The second version accepts an integer argument that explicitly sets the size of the buffer.
The third version accepts a String argument that sets the initial contents of the StringBuffer object and
reserves room for 16 more characters.
int length( )
int capacity( )
Example:
// StringBuffer length vs. capacity.
public class Ex1 {
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Sidra");
System.out.println("buffer = " + s1);
System.out.println("length = " + s1.length());
System.out.println("capacity = " + s1.capacity());
}
}
Output:
Since s1 is initialized with the string “Sidra” 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 pre-allocate room for a certain number of characters after a StringBuffer has been
constructed, you can use the ensureCapacity() to set the size of the buffer.
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the minimum to
the current capacity. If it is greater than the current capacity, it increases the capacity by
(oldcapacity*2)+2.
Syntax:
Void ensuercapacity(int capacity) // capacity specifies the size of the buffer.
setLength()
It is used to set the length of the buffer within a StringBuffer object.
Syntax:
void setLength(int len)
For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where
specifies the index of the character being set, and ch specifies the new value of that character. For both
methods, where must be non-negative and must not specify a location beyond the end of the buffer.
getChars( )
To copy a substring of a StringBuffer into an array,use the getChars() method.
Note: target array must be large enough to hold the number of characters in the specified substring.
Output:
Array before copying: 0123456789
Array after copying: 0123BCD789
append( )
The append( ) method concatenates the string representation of any other type of data to the end of the
invoking StringBuffer object.
insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple
types, plus Strings and Objects.
Index specifies the index at which point the string will be inserted into the invoking StringBuffer object.
Example:
// Demonstrate insert(),append(),charAt() and setCharAt() .
Output:
reverse( )
The characters within a StringBuffer object can be reversed using reverse( ) method.
StringBuffer reverse( )
Example:
//Using reverse() to reverse a StringBuffer
public class e5 {
public static void main(String[] args) {
StringBuffer s = new StringBuffer("Object Oriented Programming");
System.out.println(s);
s.reverse();
System.out.println(s);
} }
Output:
Object Oriented Programming
gnimmargorP detneirO tcejbO
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.
Example:
//Demonstrate delete() and deleteCharAt()
public class Ex5 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("We are doing Lab 08");
sb.delete(17, 19);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
sb.insert(16, "09");
sb.insert(0, "W");
System.out.println("After insertion: " + sb);
}
}
Output:
After delete: We are doing Lab
After deleteCharAt: e are doing Lab
After insertion: We are doing Lab 09
replace( )
StringBuffer’s method replace( ) replaces one set of characters with another set inside a StringBuffer
object.
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.
Example:
//Demonstrate replace
public class Ex5 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("We are doing Lab 08");
sb.replace(17, 19, "09");
System.out.println("After replacement: " + sb);
} }
Output:
After replacement: We are doing Lab 09
substring( )
The substring( ) method returns a portion of a StringBuffer. It has the following two forms:
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 like those defined for String Class.
Example:
Engr. Sidra Shafi Lab-09 5
SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java
System.out.println("\nStringBuffer Substring");
StringBuffer sub = new StringBuffer();
System.out.println(sub.insert(0, "We are doing lab 09 of oop!"));
System.out.println(sub.substring(13));
System.out.println(sub.substring(13,19));
Output:
StringBuffer Substring
We are doing lab 09 of oop!
lab 09 of oop!
lab 09
Other Examples:
Example 1:
//Demonstrate insert() and append()
public class Ex6 {
public static void main(String[] args) {
System.out.println("StringBuffer insert and append example!");
StringBuffer sb = new StringBuffer();
System.out.println(sb.insert(0, "richard")); //First position
int len = sb.length();//last position
System.out.println(sb.insert(len, "Deniyal")); //len was 7
System.out.println(sb.insert(6, "suzen")); //Six position
System.out.println(sb.append("Margrett"));//Always last
}
}
Output:
StringBuffer insert and append example!
richard
richardDeniyal
richarsuzendDeniyal
richarsuzendDeniyalMargrett
Example 2:
//Demonstrate the methods mentioned above
import java.util.Scanner;
public class Ex7{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String str;
System.out.print("Enter your name: ");
str = in.nextLine();
str += ",This is an example of SringBuffer class and it's functions.";
//Create an object of StringBuffer class
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
strbuf.delete(0,str.length());
strbuf.append("Hello");
System.out.println(strbuf);
in.close();
strbuf.append("World");
System.out.println(strbuf);//print HelloWorld
//insert()
strbuf.insert(5,"_Java ");
System.out.println(strbuf);//print Hello_Java World
Engr. Sidra Shafi Lab-09 6
SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java
//reverse()
strbuf.reverse();
System.out.print("Reversed string : ");
System.out.println(strbuf); //print dlroW avaJ_olleH
strbuf.reverse();
System.out.println(strbuf); //print Hello_Java World
//setCharAt()
strbuf.setCharAt(5,' ');
System.out.println(strbuf); //print Hello Java World
//charAt()
System.out.print("Character at 6th position : ");
System.out.println(strbuf.charAt(6));//print J
//substring()
System.out.print("Substring from position 3 to 6 : ");
System.out.println(strbuf.substring(3,7)); //print lo J
//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf); //print Helo java World
Output:
sb.append("Margrett");
System.out.println("index of string Margrett "+sb.indexOf("Margrett"));
System.out.println(sb);
System.out.println("index of string Margrett after 20th index is
"+sb.indexOf("Margrett", 20));
System.out.println("last index of string tt "+sb.lastIndexOf("tt"));
System.out.println("last index of string tt with index 27 is
"+sb.lastIndexOf("tt", 27));
}
}
Output:
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break
string.
Delimiters are nothing but only characters that separate tokens, for example, comma (,) colon(:)
semicolon(;). The default delimiters are the whitespace characters space, tab, and newline.
Example 1:
Following example of StringTokenizer class tokenizes a string "We are doing lab 09 of OOP"
based on whitespace.
import java.util.StringTokenizer;
public class st_token_ex1 {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("We are doing lab 09 of
OOP"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:
Engr. Sidra Shafi Lab-09 9
SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java
Below example shows how to break a string based on multiple delimiters. Each character in the
constructor’s delimiter field acts as one delimiter.
import java.util.StringTokenizer;
public class st_token_ex2 {
public static void main(String a[]){
String msg = "http://10.123.43.67:80/";
StringTokenizer st = new StringTokenizer(msg,"://.");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
Output:
Below example shows no of token count after breaking the string by delimiter. You can get
the count by using countTokens() method.
import java.util.StringTokenizer;
public class st_token_ex3 {
public static void main(String[] args) {
String msg = "We are doing lab 09 of OOP";
StringTokenizer st = new StringTokenizer(msg," ");
System.out.println("Count: "+st.countTokens());
}
}
Output:
import java.util.StringTokenizer;
public class st_token_ex4 {
public static void main(String[] args) {
String msg = "We are doing lab 09 of OOP";
StringTokenizer st = new StringTokenizer(msg," ", true);
System.out.println("Count: "+st.countTokens());
}
}
Output:
Example:
import java.util.StringTokenizer;
public class stringtokenandsplit {
Output:
Exercise: A Java program that reads a line of integers and displays each integer, and the
sum of all integers using StringTokenizer class is given. Find the error in this code.
import java.util.*;
Task 1: Marks: 5
Write a Java method using StringBuffer class to check whether a string is a valid
password.
Password rules:
A password must have at least 8 characters.
A password consists of only letters and digits.
A password must contain at least two digits.
Task 2: Marks: 5
i. Write a program, which reads a string and finds string after the first x. Let the input
string is awsxtpbcderxrtxgt then output is tpbcderxrtxgt.
************