Lect-4 String
Lect-4 String
Object Oriented
Programming
Techniques
Lecture 6: String and StringBuffer
2
Strings
• Strings are fundamental part of all computing
languages.
• At the basic level, they are just a data structure that
can hold a series of characters
• However, strings are not implemented as a
character array in Java as in other languages.
3
Strings
• Java string is a sequence of characters. They are
objects of type String.
• Once a String object is created it cannot be changed.
Stings are Immutable.
• To get changeable strings use the class called
StringBuffer.
• String and StringBuffer classes are declared final, so
there cannot be subclasses of these classes.
• The default constructor creates an empty string.
String s = new String();
4
Creating Strings
• String str = "abc"; is equivalent to:
String Operations
• The length() method returns the length of the string.
String Operations
• Characters in a string can be extracted in a
number of ways.
public char charAt(int index)
• Returns the character at the specified index.
An index ranges from 0 to length() - 1. The
first character of the sequence is at index 0,
the next at index 1, and so on, as for array
indexing.
char ch;
ch = “abc”.charAt(1); // ch = “b”
7
String Operations
• getChars() - Copies characters from this string into the
destination character array.
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
String Operations
• equals() - Compares the invoking string to the
specified object. The result is true if and only if the
argument is not null and is a String object that
represents the same sequence of characters as the
invoking object.
public boolean equals(Object anObject)
if (name.equals(name2))
System.out.println("The names are the same");
if (grade.charAt(0) == 'B')
gpa = 3.0;
if (grade.charAt(1) == '+')
gpa = gpa + 0.3;
10
Testing Strings for Equality
String Operations
• startsWith() – Tests if this string starts with the
specified prefix.
public boolean startsWith(String prefix)
“Figure”.startsWith(“Fig”); // true
“Figure”.endsWith(“re”); // true
12
String Operations
String Operations
String Operations
indexOf – Searches for the first occurrence of a character or
substring. Returns -1 if the character does not occur.
String Operations
public int indexOf(int ch, int fromIndex)-
Returns the index within this string of the first
occurrence of the specified character, starting the
search at the specified index.
String Operations
lastIndexOf() –Searches for the last occurrence of
a character or substring. The methods are similar
to indexOf().
substring() - Returns a new string that is a
substring of this string. The substring begins with
the character at the specified index and extends
to the end of this string.
public String substring(int beginIndex)
Eg: "unhappy".substring(2) returns "happy"
17
String Operations
• public String
substring(int beginIndex,
int endIndex)
Eg: "smiles".substring(1, 5) returns
"mile“
18
String Operations
concat() - Concatenates the specified string to
the end of this string.
If the length of the argument string is 0, then
this String object is returned.
Otherwise, a new String object is created,
containing the invoking string with the
contents of the str appended to it.
String Operations
• replace()- Returns a new string resulting from
replacing all occurrences of oldChar in this
string with newChar.
String Operations
• trim() - Returns a copy of the string, with leading
and trailing whitespace omitted.
public String trim()
String Operations
• The contents of the character array are copied;
subsequent modification of the character array does not
affect the newly created string.
String Operations
• toLowerCase(): Converts all of the characters in a
String to lower case.
• toUpperCase(): Converts all of the characters in this
String to upper case.
Immutability
• Once created, a string cannot be changed:
none of its methods changes the string.
• Such objects are called immutable.
• Immutable objects are convenient because
several references can point to the same
object safely: there is no danger of changing
an object through one reference without the
others being aware of the change.
24
Advantages Of Immutability
Disadvantages of Immutability
Less efficient — you need to create a new string and
throw away the old one even for small changes.
word “java"
“Java"
26
Empty Strings
StringBuilder
•StringBuilder is same as the StringBuffer , that is it stores the object in heap
and it can also be modified . The main difference between the StringBuffer and
StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe .
StringBuilder
StringBuilder()
This constructs a string builder with no characters in it and an initial
capacity of 16 characters.
StringBuilder(CharSequence seq)
This constructs a string builder that contains the same characters
as the specified CharSequence.
StringBuilder(int capacity)
This constructs a string builder with no characters in it and an initial
capacity specified by the capacity argument. capacity is the
available rooms cannot be less than zero.
StringBuilder(String str)
This constructs a string builder initialized to the contents of the
specified string.
Capacity= length+16 more characters
30
StringBuffer
• A StringBuffer is like a String, but can be
modified.
• The length and content of the StringBuffer
sequence can be changed through certain
method calls.
• StringBuffer defines three constructors:
• StringBuffer()
• StringBuffer(int size)
• StringBuffer(String str)
31
StringBuffer Operations
• The principal operations on a StringBuffer are
the append and insert methods, which are
overloaded so as to accept data of any type.
StringBuffer Operations
StringBuffer Operations
StringBuffer Operations
• replace() - Replaces the characters in a substring of
this StringBuffer with characters in the specified
String.
public StringBuffer replace(int start, int end, String
str)
StringBuffer Operations
• reverse() - The character sequence
contained in this string buffer is replaced
by the reverse of the sequence.
public StringBuffer reverse()
StringBuffer Operations
StringBuffer Operations
• ensureCapacity() method of StringBuffer
class ensures the capacity to at least equal to the
specified minimumCapacity.
• If the current capacity of StringBuffer < the argument
minimumCapacity, then a new internal array is allocated with
greater capacity.
• If the minimumCapacity argument > twice the old capacity,
plus 2 then new capacity is equal to minimumCapacity else
new capacity is equal to twice the old capacity, plus 2.
• If the minimumCapacity argument passed as parameter < 0,
this method takes no action.
StringBuffer Operations
• getChars() - Characters are copied from this string
buffer into the destination character array dst. The
first character to be copied is at index srcBegin; the
last character to be copied is at index srcEnd-1.
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
Examples: StringBuffer
StringBuffer sb = new StringBuffer(“Hello”);
sb.length(); // 5
sb.charAt(1); // e
sb.setCharAt(1,’i’); // Hillo
sb.setLength(2); // Hi
sb.append(“l”).append(“l”); // Hill
Examples: StringBuffer