You are on page 1of 31

String Manipulation

By
Rani Dubey
Examples of strings
• Char x=‘a’;
• Char y=‘m’
• .
• .
• Char b=‘v’
• A[0]=‘a’
• A[1]=‘m’
• A[2]=‘I’

• A[5]=‘v’
• A[6]=‘\0’
• String is a set of characters stored in contiguous memory locations
• String x=“Jayram”;
Syllabus
• Introduction to different classes
• String class, String buffer, String builder, String
tokenizer
• Concept of Wrapper classes
• Introduction to wrapper classes, different predefined
wrapper classes
• Predefined constructors for wrapper classes
• Conversion of types from one type(object) to another
type (primitive) and vice versa
• Concept of Auto boxing and Un boxing
String
• String s1=“Welcome”
• String s2=“Welcome”
• If s1==s2(true)(reference is same)

• String a=new String(“Amitav”)


• String b=new String (“Amitav”)
• If a==b(false)
What is String?
• Strings in Java are Objects that are backed
internally by a char array.
• Since arrays are immutable(cannot grow), Strings
are immutable as well.
• Whenever a change to a String is made, an
entirely new String is created.
• <String_Type> <string_variable> =
“<sequence_of_string>”;
String Diagram
StringBuffer
• Java StringBuffer class is like a string class which
accommodate change.
• used to create mutable (modifiable) string.
• StringBuffer is a peer class of String that provides much of
the functionality of strings.
• String represents fixed-length, immutable character
sequences while StringBuffer represents growable and
writable character sequences.
• StringBuffer may have characters and substrings inserted in
the middle or appended to the end.
• It will automatically grow to make room for such additions
and often has more characters preallocated than are
actually needed, to allow room for growth
StringBuffer Constructors
• StringBuffer( ): It reserves room for 16 characters
without reallocation
– E.g. StringBuffer s=new StringBuffer();
• StringBuffer( int size)It accepts an integer argument
that explicitly sets the size of the buffer
– E.g. StringBuffer s=new StringBuffer(50);
• StringBuffer(String str): It accepts a String argument
that sets the initial contents of the StringBuffer object
and reserves room for 16 more characters without
reallocation.
– E.g. StringBuffer s=new StringBuffer(“Amitav Saran");
Methods
• length( ) : The length of a StringBuffer can be found by the
length( ) method,
• capacity( ): the total allocated capacity can be found by the
capacity( ) method
• append() is used to add text at the end of the existence text
– StringBuffer append(String str)
– StringBuffer append(int num)
• insert()  is used to insert text at the specified index position.
– StringBuffer insert(int index, String str)
– StringBuffer insert(int index, char ch)
Methods
• reverse(): can reverse the characters within a StringBuffer
object
• This method returns the reversed object on which it was
called. 
• We can delete characters within a StringBuffer by using
methods delete() and deleteCharAt( ).
– StringBuffer delete(int startIndex, int endIndex)
– StringBuffer deleteCharAt(int loc)
• We can replace one set of characters with another set inside
a StringBuffer object by calling replace( )
– StringBuffer replace(int startIndex, int endIndex, String str)
String Builder
• Java StringBuilder class is used to create
mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class
except that it is non-synchronized
Constructor
Constructor Description
StringBuilder() creates an empty string Builder
with the initial capacity of 16.
StringBuilder(String str) creates a string Builder with the
specified string.
StringBuilder(int length) creates an empty string Builder
with the specified capacity as
length
Method Description
public StringBuilder append(String s) is used to append the specified string
with this string. The append() method
is overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.

public StringBuilder insert(int offset, is used to insert the specified string


String s) with this string at the specified
position. The insert() method is
overloaded like insert(int, char),
insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double)
etc.

public StringBuilder replace(int is used to replace the string from


startIndex, int endIndex, String str) specified startIndex and endIndex.

public StringBuilder delete(int is used to delete the string from


startIndex, int endIndex) specified startIndex and endIndex.
public StringBuilder reverse() is used to reverse the string.
public int capacity() is used to return the current
capacity.

public void ensureCapacity(int is used to ensure the capacity at


minimumCapacity) least equal to the given minimum.

public char charAt(int index) is used to return the character at


the specified position.

public int length() is used to return the length of the


string i.e. total number of
characters.

public String substring(int is used to return the substring


beginIndex) from the specified beginIndex.

public String substring(int is used to return the substring


beginIndex, int endIndex) from the specified beginIndex and
endIndex.
Difference
No. StringBuffer StringBuilder
1) StringBuffer StringBuilder is non-
is synchronized i.e. thread synchronized i.e. not
safe. It means two threads thread safe. It means
can't call the methods of two threads can call the
StringBuffer simultaneously. methods of
StringBuilder
simultaneously.
2) StringBuffer is less StringBuilder is more
efficient than StringBuilder. efficient than
StringBuffer.
String Tokenizer
• The java.util.StringTokenizer class allows to
break a string into tokens.
• It is simple way to break string.
• It doesn't provide the facility to differentiate
numbers, quoted strings, identifiers etc. like
StreamTokenizer (I/O) class.
String tokenizer class
• The java.util.StringTokenizer class allows you to break a String into tokens.
It is simple way to break a String. It is a legacy class of Java.
• It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like StreamTokenizer class. We will discuss about the
StreamTokenizer class in I/O chapter.
• In the StringTokenizer class, the delimiters can be provided at the time of
creation or one by one to the tokens.
Process flow
Simple program
• import java.util.StringTokenizer;
• public class Simple{
• public static void main(String args[]){
• StringTokenizer st = new StringTokenizer("my name is
khan"," ");
• while (st.hasMoreTokens()) {
• System.out.println(st.nextToken());
• }
• }
• }
output
My
Name
Is
Khan
nextToken
• import java.util.*;

• public class Test {
• public static void main(String[] args) {
• StringTokenizer st = new
StringTokenizer("my,name,is,khan");

• // printing next token
• System.out.println("Next token is : " + st.nextToken(","));
• }
• }
output
• Next Token is : My
hasMoreElements
1.;    
import java.util.StringTokenizer
2.public class StringTokenizer2  
3.{    
4.args[])  
 public static void main(String 
5. {    
6.gTokenizer("Hello everyone I a
 m a Java developer"," ");    
  StringTokenizer st = new Strin
7.)   
     while (st.hasMoreElements()
8.     {    
9.oken());    
         System.out.println(st.nextT
10.     }    
11. }    
12.}  
output

Hello
Everyone
I
Am
A
Java
developer
countTokens() method
Constructor
Constructor Description
StringTokenizer(String str) creates StringTokenizer with
specified string.
StringTokenizer(String str, String creates StringTokenizer with
delim) specified string and delimeter.
StringTokenizer(String str, String creates StringTokenizer with
delim, boolean returnValue) specified string, delimeter and
returnValue. If return value is
true, delimiter characters are
considered to be tokens. If it is
false, delimiter characters serve
to separate tokens.
Methods
Public method Description
boolean hasMoreTokens() checks if there is more tokens
available.
String nextToken() returns the next token from the
StringTokenizer object.
String nextToken(String delim) returns the next token based on
the delimeter.
boolean hasMoreElements() same as hasMoreTokens()
method.
Object nextElement() same as nextToken() but its
return type is Object.
int countTokens() returns the total number of
tokens.
Concept of Wrapper classes
• The wrapper classes in Java provide the
mechanism to convert primitive into object and
object into primitive.
• A Wrapper class is a class whose object wraps or
contains primitive data types.
• When we create an object to a wrapper class, it
contains a field and in this field, we can store
primitive data types.
• The automatic conversion of primitive into an
object is known as autoboxing and vice-versa
unboxing.
Need of Wrapper Classes
• Change the value in Method: Java supports only call by value. So, if we
pass a primitive value, it will not change the original value. But, if we
convert the primitive value in an object, it will change the original value.
• Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects
through the wrapper classes.
• Synchronization: Java synchronization works with objects in
Multithreading.
• java.util package: The java.util package provides the utility classes to deal
with objects.
• Collection Framework: Java collection framework works with objects only.
All classes of the collection framework (ArrayList, LinkedList, Vector,
HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal
with objects only.
Autoboxing
• The automatic conversion of primitive data
type into its corresponding wrapper class is
known as autoboxing, for example, byte to
Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean,
double to Double, and short to Short.
• Since Java 5, we do not need to use the
valueOf() method of wrapper classes to
convert the primitive into objects.
Unboxing
• The automatic conversion of wrapper type
into its corresponding primitive type is known
as unboxing.
• It is the reverse process of autoboxing.
• Since Java 5, we do not need to use the
intValue() method of wrapper classes to
convert the wrapper type into primitives.

You might also like