Lab 09 Java - 2k22

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

UET TAXILA

CLO Learning Outcomes Assessment Item BT Level PLO


No.

1 Construct the experiments / Lab Task, Mid Exam, Final


projects of varying complexities. Exam, Quiz, Assignment, P2 3
Semester Project
2 Use modern tool and languages. Lab Task, Semester
P2 5
Project
3 Demonstrate an original solution of Lab Task, Semester
A2 8
problem under discussion. Project
4 Work individually as well as in Lab Task, Semester A2 9
teams Project

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.

The StringBuffer class


StringBuffer is a peer class of String that provides much of the functionality of strings. String represents
fixed-length, immutable character sequences. In contrast, StringBuffer represents growable and
writeable 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
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.

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( )

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

Engr. Sidra Shafi Lab-09 1


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

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)

public class Ex2 {


public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Sidra Shafi");
System.out.println("length = " + s1.length());
s1.setLength(6);
System.out.println("length created = " + s1.length());
System.out.println("s1 after making changes = " + s1);
}
}
Output:
length = 11
length created = 6
s1 after making changes = Sidra

charAt( ) and setCharAt( )


The value of a single character can be obtained from a StringBuffer via the charAt( )method. You can
set the value of a character within a StringBuffer using setCharAt( ).

char charAt(int where)


void setCharAt(int where, char ch)

Engr. Sidra Shafi Lab-09 2


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

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.

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

Note: target array must be large enough to hold the number of characters in the specified substring.

public class Ex3 {


public static void main(String args[])
{
StringBuffer sb1 = new StringBuffer("ABCDEFGHI");
char ch[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
System.out.println("Array before copying: " + new String(ch));
sb1.getChars(1, 4, ch, 4);
System.out.println("Array after copying: " + new String(ch));
} }

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.

StringBuffer append(String str)


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

String.valueOf( ) is called for each parameter to obtain its string representation.


The result is appended to the current StringBuffer object. The buffer itself is returned by each version
of append( ).

insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple
types, plus Strings and Objects.

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

Index specifies the index at which point the string will be inserted into the invoking StringBuffer object.

Example:
// Demonstrate insert(),append(),charAt() and setCharAt() .

public class Ex4 {

Engr. Sidra Shafi Lab-09 3


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

public static void main(String[] args) {


StringBuffer sb = new StringBuffer(" in ");
sb.append("God");
sb.append('!');
sb.insert(0,"Believe");
sb.append('\n');
sb.append("God is Great");
char c=sb.charAt(20);
System.out.println("character at index 20 is: "+c);
sb.setCharAt(20,'I');
System.out.println(sb);
}
}

Output:

reverse( )
The characters within a StringBuffer object can be reversed using reverse( ) method.

StringBuffer reverse( )

This method returns the reversed object on which it was called.

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

delete( ) and deleteCharAt( )


In StringBuffer, the characters can be deleted using the methods delete( ) and deleteCharAt( ).

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.

Engr. Sidra Shafi Lab-09 4


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

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.

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.

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:

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 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

//delete() and length()


strbuf.delete(6,strbuf.length());
System.out.println(strbuf); //Helo J
}
}

Output:

Other methods of StringBuffer class:

Engr. Sidra Shafi Lab-09 7


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

public class Ex8 {


public static void main(String[] args) {
System.out.println("StringBuffer indexOf and lastIndexOf 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"));
System.out.println(sb.insert(6, "suzen")); //Six position
System.out.println(sb.append("Margrett"));//Always last

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.

Engr. Sidra Shafi Lab-09 8


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

Constructors of StringTokenizer class:


There are 3 constructors defined in the StringTokenizer class.

Methods of StringTokenizer class:

The 6 useful methods of StringTokenizer class are as follows:

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

Example 2: Java StringTokenizer With Multiple De-limiters

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:

Example 3: Java StringTokenizer Token Count

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:

Example 4: Java StringTokenizer third constructor

Below example shows tokens including delimiter as token using constructor 3.

Engr. Sidra Shafi Lab-09 10


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

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 {

public static void main(String[] args) {


String delims = ",";
String splitString = "one,two,,three,four,,five";

System.out.println("StringTokenizer Example: \n");


StringTokenizer st = new StringTokenizer(splitString, delims);
while (st.hasMoreElements()) {
System.out.println("StringTokenizer Output: " +
st.nextElement());
}
System.out.println("\n\nSplit Example: \n");
String[] tokens = splitString.split(delims);
int tokenCount = tokens.length;
for (int j = 0; j < tokenCount; j++) {
System.out.println("Split Output: "+ tokens[j]);
} } }

Output:

Engr. Sidra Shafi Lab-09 11


SSShafiemester
4thSemester Lab-09: StringBuffer and StringTokenizer class in Java

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.*;

public class LabExercise {

public static void main(String[] args) {


int n;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter integers with one space gap:");
String s = sc.nextLine();
StringTokenizer st = new StringTokenizer(s, " ");
while (st.hasMoreTokens()) {
String temp = st.nextToken();
sum = sum + temp;
}
System.out.println("sum of the integers is: " + sum);
sc.close();

Lab Tasks Marks:10

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.

ii. Write program to output the location of second x.

************

Engr. Sidra Shafi Lab-09 12


SSShafiemester

You might also like