SlideShare a Scribd company logo
1 of 20
Download to read offline
StringBuffer and its functions, StringTokenizer, its functions and its working
A string buffer is like a String, but can be modified. At any point in time it contains some
particular sequence of characters, but the length and content of the sequence can be
changed through certain method calls.
Creating object:
StringBuffer sb=new StringBuffer(“Hello”);
or
String s=“Hello”;
StringBuffer sb=new StringBuffer(s);
StringBuffer append(Any Data Type)- Appends the specified CharSequence to this sequence
StringBuffer s=new StringBuffer(“Hello”);
s.append(“ Java”); //s will be updated
System.out.print(s);
will print Hello Java
System.out.print(s.append(123));
will print Hello123
s=s.append(5.69); //s will be updated
System.out.print(s);
will print Hello5.69
• int length()- returns the length of string
StringBuffer s=new StringBuffer(“Hello”);
int len=s.length();
System.out.print(len);
will print 5
• char charAt(int index) – returns the character at given index
StringBuffer s1=new StringBuffer(“ABCDEFG”);
System.out.print(s1.charAt(3));
will print D
• int indexOf(String str)- returns the first index from where given string starts
int indexOf(String str,int fromIndex)- returns the first index from where given string
starts after the fromIndex. fromIndex - the index from which to start the search
StringBuffer s1=new StringBuffer(“ABCDEFABCDEF”);
System.out.print(s1. indexOf(“BCD”));
will print 1
System.out.print(s1. indexOf(“B”,5));
will print 7
• int lastIndexOf (String str)- returns the last index from where given string starts
int lastIndexOf(String str,int last)- returns the last index from where given string starts
before the last index. last is included
StringBuffer s1=new StringBuffer(“ABCDEFABCDEF”);
System.out.print(s1. lastIndexOf(“BCD”));
will print 7
• StringBuffer reverse()- Causes this character sequence to be replaced by the reverse of
the sequence.
StringBuffer sb=new StringBuffer(“ABCDEFG”);
sb.reverse();
System.out.print(sb);
will print GFEDCBA
A B C D E F A B C D E F
0 1 2 3 4 5 6 7 8 9 10 11
• Boolean equals(Object obj)- Indicates whether some other object obj is "equal to" this
one
StringBuffer sb=new StringBuffer("Hello");
StringBuffer s=new StringBuffer("Hello");
if(s.equals(sb))
System.out.println("True");
else
System.out.println("false");
will print false because sb and s contains different references or you can say that both sb
and s points to different objects(has different address).
StringBuffer sb=new StringBuffer("Hello");
StringBuffer s=sb;
if(s.equals(sb))
System.out.println("True");
else
System.out.println("false");
will print true because sb and s contains same references or you can say that both sb and s
points to same objects(has same address).
• String substring(int start)- Returns a new String that contains a subsequence of
characters currently contained in this character sequence. The substring begins at the
specified index and extends to the end of this sequence. ‘start’ is included.
StringBuffer s1=new StringBuffer(“ABCDEF”);
System.out.print(s1. substring(3));
will print DEF
• String substring(int start,int end)- returns substring from ‘start’ index to ‘end’ index.
‘start’ is included while ‘end’ is excluded
StringBuffer s1=new StringBuffer(“ABCDEF”);
System.out.print(s1. substring(2,5));
will print CDE
A B C D E F
0 1 2 3 4 5
• StringBuffer replace(int start, int end, String str)- Replaces the characters in a
substring of this sequence with characters in the specified String.
start - The beginning index, inclusive.
end - The ending index, exclusive.
str - String that will replace previous contents
StringBuffer s1=new StringBuffer(“ABCDEF”);
s1.replace(0,2,”Hello ”);
System.out.print(s1);
will print Hello CDEF
• StringBuffer delete(int start,int end)- delete the string from index start to end-1
StringBuffer s1=new StringBuffer(“ABCDEF”);
s1.delete(0,3);
System.out.print(s1);
will print DEF
A B C D E F
0 1 2 3 4 5
• StringBuffer insert(int start, Any data Type)- insert the given type at index start and
shifts forward the remaining characters
start - The beginning index
StringBuffer s1=new StringBuffer(“ABCDEF”);
s1.insert(3,”Hello ”);
System.out.print(s1);
will print ABCHelloDEF
• StringBuffer deleteCharAt(int index)- deletes the character at given index
StringBuffer s1=new StringBuffer(“ABCDEF”);
s1.deleteCharAt(3);
System.out.print(s1);
will print ABCEF
A B C D E F
0 1 2 3 4 5
• StringBuffer setCharAt(int index, char ch)- set character at index to given character ch
StringBuffer s1=new StringBuffer(“ABCDEF”);
s1.setCharAt(3,’#’);
System.out.print(s1);
will print ABC#EF
• String toString()- converts the given StringBuffer to String
StringBuffer s1=new StringBuffer(“ABCDEF”);
String s=s1.toString();
System.out.print(s);
will print ABCDEF
Now to convert the given String to StringBufffer you can use:
String s=“hello”;
StringBuffer sb=new StringBuffer(s);
or
StringBuffer sb=new StringBuffer(“Hello”);
A B C D E F
0 1 2 3 4 5
The string tokenizer class allows an application to break a string into tokens.
Creating object:
StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”);
or
String s=“Hello this is GsbProgramming”;
StringTokenizer st=new StringTokenizer(s);
The default delimiter(after which a new token will be started) is SPACE
so, st has following tokens:
1. Hello
2. this
3. is
4. GsbProgramming
You can specify your own delimiters also. For example:
StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “,”);
Now delimiter will be comma(,)
Now st has following tokens:
1. Hello
2. this is
3. GsbProgramming
StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “”);
will have only one token:
1. Hello,this is,Gsbprogramming
Suppose if you want that delimiter will also be a token then you can make object like:
StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “,”,true);
now st will have following tokens:
1. Hello
2. ,
3. this is
4. ,
5. GsbProgramming
if you specify true then delimiters will also be counted as token, if you specify false
delimiters will not be taken as a token
You can also specify more than one delimiters as:
StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “, ”);
delimiters are comma(,) and space
Here st will have following tokens:
1. Hello
2. this
3. is
4. Gsbprogramming
StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “, ”,true);
now st will have following tokens:
1. Hello
2. ,
3. this
4. (space)
5. is
6. ,
7. GsbProgramming
• int countTokens()- returns the total tokens left at given time.
StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”);
System.out.println(“Total Tokens: ”+st.countTokens());
will print Total Tokens: 4
• String nextToken()- returns the next token, and advances the pointer
StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”);
System.out.println(“First Token: ”+st.nextToken());
will print: First Token: Hello
• boolean hasMoreToken()- returns true if any token is left for processing otherwise
returns false
StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”);
if(st.hasMoreToken())
{
System.out.print(“Token is Available”);
}
will print: Token is Available
StringTokenizer maintains a cursor or pointer that points to current token.
For example:
StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”);
when we write this statement it will convert the string “Hello this is Gsbprogramming” into
tokens and place the pointer at first token
Tokens:
Current position of pointer
So when we write st.countTokens() it will return 4 because total tokens after the
pointer(including token at current position ) are 4
Therefore st.hasMoreToken() will return true
Token 1 Token 2 Token 3 Token 4
Hello this is GsbProgramming
now if we write st.nextToken() it will return the token at current position of pointer, i.e. it
will return Hello and advances the position of pointer as below:
Current position of pointer
So when we write st.countTokens() it will return 3 because total tokens after the
pointer(including token at current position ) are 3
Therefore st.hasMoreToken() will return true
Token 1 Token 2 Token 3 Token 4
Hello this is GsbProgramming
now if we again write st.nextToken() it will return the token at current position of pointer,
i.e. it will return this and advances the position of pointer as below:
Current position of pointer
So when we write st.countTokens() it will return 2 because total tokens after the
pointer(including token at current position ) are 2
Therefore st.hasMoreToken() will return true
Token 1 Token 2 Token 3 Token 4
Hello this is GsbProgramming
now if we again write st.nextToken() it will return the token at current position of pointer,
i.e. it will return is and advances the position of pointer as below:
Current position of pointer
So when we write st.countTokens() it will return 1 because total tokens after the
pointer(including token at current position ) are 1
Therefore st.hasMoreToken() will return true
Token 1 Token 2 Token 3 Token 4
Hello this is GsbProgramming
now if we again write st.nextToken() it will return the token at current position of pointer,
i.e. it will return GsbProgramming and deletes pointer as below:
So when we write st.countTokens() it will return 0 because there is no tokens after the
pointer(including token at current position )
Therefore st.hasMoreToken() will return false
Now if we write st.nextToken() it will generate an exception: NoSuchElementException
Token 1 Token 2 Token 3 Token 4
Hello this is GsbProgramming
For more Visit:
http://gsb-programming.blogspot.in/search/label/Java

More Related Content

What's hot

Functions in python
Functions in pythonFunctions in python
Functions in python
Ilian Iliev
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
웅식 전
 

What's hot (20)

Alias
AliasAlias
Alias
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
 
String (Computer programming and utilization)
String (Computer programming and utilization)String (Computer programming and utilization)
String (Computer programming and utilization)
 
Pythonintroduction
PythonintroductionPythonintroduction
Pythonintroduction
 
Unitii string
Unitii stringUnitii string
Unitii string
 
Pratt Parser in Python
Pratt Parser in PythonPratt Parser in Python
Pratt Parser in Python
 
strings
stringsstrings
strings
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Slicing
SlicingSlicing
Slicing
 
Python
PythonPython
Python
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Fundamentals of Cryptography - Caesar Cipher - Python
Fundamentals of Cryptography - Caesar Cipher - Python Fundamentals of Cryptography - Caesar Cipher - Python
Fundamentals of Cryptography - Caesar Cipher - Python
 
Unit vii wp ppt
Unit vii wp pptUnit vii wp ppt
Unit vii wp ppt
 
String Methods and Files
String Methods and FilesString Methods and Files
String Methods and Files
 
Iteration
IterationIteration
Iteration
 
14 strings
14 strings14 strings
14 strings
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 

Viewers also liked

Chapter3 basic java data types and declarations
Chapter3 basic java data types and declarationsChapter3 basic java data types and declarations
Chapter3 basic java data types and declarations
sshhzap
 

Viewers also liked (14)

Learn Java Part 9
Learn Java Part 9Learn Java Part 9
Learn Java Part 9
 
Stars
StarsStars
Stars
 
Learn Java Part 11
Learn Java Part 11Learn Java Part 11
Learn Java Part 11
 
Learn Java Part 8
Learn Java Part 8Learn Java Part 8
Learn Java Part 8
 
Learn Java Part 5
Learn Java Part 5Learn Java Part 5
Learn Java Part 5
 
Learn Java Part 4
Learn Java Part 4Learn Java Part 4
Learn Java Part 4
 
Defing locations in Oracle Apps
Defing locations in Oracle AppsDefing locations in Oracle Apps
Defing locations in Oracle Apps
 
Learn Java Part 10
Learn Java Part 10Learn Java Part 10
Learn Java Part 10
 
Assigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYSTAssigning role AME_BUS_ANALYST
Assigning role AME_BUS_ANALYST
 
Creating business group in oracle apps
Creating business group in oracle appsCreating business group in oracle apps
Creating business group in oracle apps
 
Learn Java Part 1
Learn Java Part 1Learn Java Part 1
Learn Java Part 1
 
Learn Java Part 2
Learn Java Part 2Learn Java Part 2
Learn Java Part 2
 
Chapter3 basic java data types and declarations
Chapter3 basic java data types and declarationsChapter3 basic java data types and declarations
Chapter3 basic java data types and declarations
 
Introduction to Jquery
Introduction to JqueryIntroduction to Jquery
Introduction to Jquery
 

Similar to Learn Java Part 7

String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

Similar to Learn Java Part 7 (20)

Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 
Strings
StringsStrings
Strings
 
StringBuffer.pptx
StringBuffer.pptxStringBuffer.pptx
StringBuffer.pptx
 
Java string handling
Java string handlingJava string handling
Java string handling
 
07slide
07slide07slide
07slide
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
M C6java7
M C6java7M C6java7
M C6java7
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
Python String Revisited.pptx
Python String Revisited.pptxPython String Revisited.pptx
Python String Revisited.pptx
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
String functions
String functionsString functions
String functions
 
Strings
StringsStrings
Strings
 

More from Gurpreet singh

More from Gurpreet singh (20)

Introduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP ReportingIntroduction to Oracle Fusion BIP Reporting
Introduction to Oracle Fusion BIP Reporting
 
Why Messaging system?
Why Messaging system?Why Messaging system?
Why Messaging system?
 
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...Understanding Flex Fields with  Accounting Flexfields(Chart of Accounts) in O...
Understanding Flex Fields with Accounting Flexfields(Chart of Accounts) in O...
 
Oracle Application Developmenr Framework
Oracle Application Developmenr FrameworkOracle Application Developmenr Framework
Oracle Application Developmenr Framework
 
Java Servlet part 3
Java Servlet part 3Java Servlet part 3
Java Servlet part 3
 
Oracle advanced queuing
Oracle advanced queuingOracle advanced queuing
Oracle advanced queuing
 
Oracle SQL Part 3
Oracle SQL Part 3Oracle SQL Part 3
Oracle SQL Part 3
 
Oracle SQL Part 2
Oracle SQL Part 2Oracle SQL Part 2
Oracle SQL Part 2
 
Oracle SQL Part1
Oracle SQL Part1Oracle SQL Part1
Oracle SQL Part1
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
IO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxingIO Streams, Serialization, de-serialization, autoboxing
IO Streams, Serialization, de-serialization, autoboxing
 
Java Servlets Part 2
Java Servlets Part 2Java Servlets Part 2
Java Servlets Part 2
 
PL/SQL Part 5
PL/SQL Part 5PL/SQL Part 5
PL/SQL Part 5
 
PL/SQL Part 3
PL/SQL Part 3PL/SQL Part 3
PL/SQL Part 3
 
PL/SQL Part 2
PL/SQL Part 2PL/SQL Part 2
PL/SQL Part 2
 
PL/SQL Part 1
PL/SQL Part 1PL/SQL Part 1
PL/SQL Part 1
 
Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)Introduction to Data Flow Diagram (DFD)
Introduction to Data Flow Diagram (DFD)
 
Ingenium test(Exam Management System) Project Presentation (Full)
Ingenium test(Exam Management System) Project Presentation (Full)Ingenium test(Exam Management System) Project Presentation (Full)
Ingenium test(Exam Management System) Project Presentation (Full)
 
Computer Graphics Notes
Computer Graphics NotesComputer Graphics Notes
Computer Graphics Notes
 
Learn Java Part 11
Learn Java Part 11Learn Java Part 11
Learn Java Part 11
 

Recently uploaded

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 

Recently uploaded (20)

Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 

Learn Java Part 7

  • 1. StringBuffer and its functions, StringTokenizer, its functions and its working
  • 2. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. Creating object: StringBuffer sb=new StringBuffer(“Hello”); or String s=“Hello”; StringBuffer sb=new StringBuffer(s);
  • 3. StringBuffer append(Any Data Type)- Appends the specified CharSequence to this sequence StringBuffer s=new StringBuffer(“Hello”); s.append(“ Java”); //s will be updated System.out.print(s); will print Hello Java System.out.print(s.append(123)); will print Hello123 s=s.append(5.69); //s will be updated System.out.print(s); will print Hello5.69
  • 4. • int length()- returns the length of string StringBuffer s=new StringBuffer(“Hello”); int len=s.length(); System.out.print(len); will print 5 • char charAt(int index) – returns the character at given index StringBuffer s1=new StringBuffer(“ABCDEFG”); System.out.print(s1.charAt(3)); will print D • int indexOf(String str)- returns the first index from where given string starts int indexOf(String str,int fromIndex)- returns the first index from where given string starts after the fromIndex. fromIndex - the index from which to start the search StringBuffer s1=new StringBuffer(“ABCDEFABCDEF”); System.out.print(s1. indexOf(“BCD”)); will print 1 System.out.print(s1. indexOf(“B”,5)); will print 7
  • 5. • int lastIndexOf (String str)- returns the last index from where given string starts int lastIndexOf(String str,int last)- returns the last index from where given string starts before the last index. last is included StringBuffer s1=new StringBuffer(“ABCDEFABCDEF”); System.out.print(s1. lastIndexOf(“BCD”)); will print 7 • StringBuffer reverse()- Causes this character sequence to be replaced by the reverse of the sequence. StringBuffer sb=new StringBuffer(“ABCDEFG”); sb.reverse(); System.out.print(sb); will print GFEDCBA A B C D E F A B C D E F 0 1 2 3 4 5 6 7 8 9 10 11
  • 6. • Boolean equals(Object obj)- Indicates whether some other object obj is "equal to" this one StringBuffer sb=new StringBuffer("Hello"); StringBuffer s=new StringBuffer("Hello"); if(s.equals(sb)) System.out.println("True"); else System.out.println("false"); will print false because sb and s contains different references or you can say that both sb and s points to different objects(has different address). StringBuffer sb=new StringBuffer("Hello"); StringBuffer s=sb; if(s.equals(sb)) System.out.println("True"); else System.out.println("false"); will print true because sb and s contains same references or you can say that both sb and s points to same objects(has same address).
  • 7. • String substring(int start)- Returns a new String that contains a subsequence of characters currently contained in this character sequence. The substring begins at the specified index and extends to the end of this sequence. ‘start’ is included. StringBuffer s1=new StringBuffer(“ABCDEF”); System.out.print(s1. substring(3)); will print DEF • String substring(int start,int end)- returns substring from ‘start’ index to ‘end’ index. ‘start’ is included while ‘end’ is excluded StringBuffer s1=new StringBuffer(“ABCDEF”); System.out.print(s1. substring(2,5)); will print CDE A B C D E F 0 1 2 3 4 5
  • 8. • StringBuffer replace(int start, int end, String str)- Replaces the characters in a substring of this sequence with characters in the specified String. start - The beginning index, inclusive. end - The ending index, exclusive. str - String that will replace previous contents StringBuffer s1=new StringBuffer(“ABCDEF”); s1.replace(0,2,”Hello ”); System.out.print(s1); will print Hello CDEF • StringBuffer delete(int start,int end)- delete the string from index start to end-1 StringBuffer s1=new StringBuffer(“ABCDEF”); s1.delete(0,3); System.out.print(s1); will print DEF A B C D E F 0 1 2 3 4 5
  • 9. • StringBuffer insert(int start, Any data Type)- insert the given type at index start and shifts forward the remaining characters start - The beginning index StringBuffer s1=new StringBuffer(“ABCDEF”); s1.insert(3,”Hello ”); System.out.print(s1); will print ABCHelloDEF • StringBuffer deleteCharAt(int index)- deletes the character at given index StringBuffer s1=new StringBuffer(“ABCDEF”); s1.deleteCharAt(3); System.out.print(s1); will print ABCEF A B C D E F 0 1 2 3 4 5
  • 10. • StringBuffer setCharAt(int index, char ch)- set character at index to given character ch StringBuffer s1=new StringBuffer(“ABCDEF”); s1.setCharAt(3,’#’); System.out.print(s1); will print ABC#EF • String toString()- converts the given StringBuffer to String StringBuffer s1=new StringBuffer(“ABCDEF”); String s=s1.toString(); System.out.print(s); will print ABCDEF Now to convert the given String to StringBufffer you can use: String s=“hello”; StringBuffer sb=new StringBuffer(s); or StringBuffer sb=new StringBuffer(“Hello”); A B C D E F 0 1 2 3 4 5
  • 11. The string tokenizer class allows an application to break a string into tokens. Creating object: StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”); or String s=“Hello this is GsbProgramming”; StringTokenizer st=new StringTokenizer(s); The default delimiter(after which a new token will be started) is SPACE so, st has following tokens: 1. Hello 2. this 3. is 4. GsbProgramming You can specify your own delimiters also. For example: StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “,”); Now delimiter will be comma(,)
  • 12. Now st has following tokens: 1. Hello 2. this is 3. GsbProgramming StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “”); will have only one token: 1. Hello,this is,Gsbprogramming Suppose if you want that delimiter will also be a token then you can make object like: StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “,”,true); now st will have following tokens: 1. Hello 2. , 3. this is 4. , 5. GsbProgramming if you specify true then delimiters will also be counted as token, if you specify false delimiters will not be taken as a token
  • 13. You can also specify more than one delimiters as: StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “, ”); delimiters are comma(,) and space Here st will have following tokens: 1. Hello 2. this 3. is 4. Gsbprogramming StringTokenizer st=new StringTokenizer(“Hello,this is,GsbProgramming”, “, ”,true); now st will have following tokens: 1. Hello 2. , 3. this 4. (space) 5. is 6. , 7. GsbProgramming
  • 14. • int countTokens()- returns the total tokens left at given time. StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”); System.out.println(“Total Tokens: ”+st.countTokens()); will print Total Tokens: 4 • String nextToken()- returns the next token, and advances the pointer StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”); System.out.println(“First Token: ”+st.nextToken()); will print: First Token: Hello • boolean hasMoreToken()- returns true if any token is left for processing otherwise returns false StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”); if(st.hasMoreToken()) { System.out.print(“Token is Available”); } will print: Token is Available
  • 15. StringTokenizer maintains a cursor or pointer that points to current token. For example: StringTokenizer st=new StringTokenizer(“Hello this is GsbProgramming”); when we write this statement it will convert the string “Hello this is Gsbprogramming” into tokens and place the pointer at first token Tokens: Current position of pointer So when we write st.countTokens() it will return 4 because total tokens after the pointer(including token at current position ) are 4 Therefore st.hasMoreToken() will return true Token 1 Token 2 Token 3 Token 4 Hello this is GsbProgramming
  • 16. now if we write st.nextToken() it will return the token at current position of pointer, i.e. it will return Hello and advances the position of pointer as below: Current position of pointer So when we write st.countTokens() it will return 3 because total tokens after the pointer(including token at current position ) are 3 Therefore st.hasMoreToken() will return true Token 1 Token 2 Token 3 Token 4 Hello this is GsbProgramming
  • 17. now if we again write st.nextToken() it will return the token at current position of pointer, i.e. it will return this and advances the position of pointer as below: Current position of pointer So when we write st.countTokens() it will return 2 because total tokens after the pointer(including token at current position ) are 2 Therefore st.hasMoreToken() will return true Token 1 Token 2 Token 3 Token 4 Hello this is GsbProgramming
  • 18. now if we again write st.nextToken() it will return the token at current position of pointer, i.e. it will return is and advances the position of pointer as below: Current position of pointer So when we write st.countTokens() it will return 1 because total tokens after the pointer(including token at current position ) are 1 Therefore st.hasMoreToken() will return true Token 1 Token 2 Token 3 Token 4 Hello this is GsbProgramming
  • 19. now if we again write st.nextToken() it will return the token at current position of pointer, i.e. it will return GsbProgramming and deletes pointer as below: So when we write st.countTokens() it will return 0 because there is no tokens after the pointer(including token at current position ) Therefore st.hasMoreToken() will return false Now if we write st.nextToken() it will generate an exception: NoSuchElementException Token 1 Token 2 Token 3 Token 4 Hello this is GsbProgramming