Module 3 Notes
Module 3 Notes
VISION
The Department of Information Science and Engineering strives to be a centre of
learning in the field of Information Technology to produce globally competent
engineers catering to the needs of the industry and society.
MISSION
PROGRAM OUTCOMES
Engineering graduates in Information Science and Engineering will be able to:
Rubrics for course articulation level: 66% and above – Articulation Level 3
From 34% up to 65% - Articulation level 2
33% and below – Articulation level 1
Module – 3
String Handling
The String Constructors
String Length
Special String Operations
o String Literals
o String Concatenation
o String Concatenation with Other Data Types
String Conversion and toString( )
Character Extraction
o charAt( ), getChars( ), getBytes( ) toCharArray(),
String Comparison
o equals( ) and equalsIgnoreCase( ), regionMatches( ) startsWith( ) and endsWith(
), equals() Versus == , compareTo( )
Searching Strings
Modifying a String
o substring( ), concat( ), replace( ), trim( )
Data Conversion Using valueOf( )
Changing the Case of Characters Within a String
Additional String Methods
StringBuffer ,
StringBuffer Constructors
o length( ) and capacity( ), ensureCapacity( ),
o setLength( ), charAt( ) and setCharAt( ), getChars( ),append( ), insert( ), reverse(
), delete( ) and deleteCharAt( ), replace( ), substring( )
Additional StringBuffer
Methods, StringBuilder
String() To create an empty String, you call the default constructor. For example,
1 String s = new String();
will create an instance of String with no characters in it.
String(byte[] bytes)
The String class provides constructors that initialize a string when given a byte array.
2
Their forms are shown here: String(byte asciiChars[ ])
Here, asciiChars specifies the array of bytes
String(String obj)
This initializes a newly created String object so that it represents the same sequence of
4
characters as the argument; in other words, the newly created string is a copy of the
argument string.
String(StringBuffer buffer)
5 This allocates a new string that contains the sequence of characters currently contained in
the string buffer argument.
String(StringBuilder builder)
6 This allocates a new string that contains the sequence of characters currently contained in
the string builder argument.
String(char[] value)
8 This allocates a new String so that it represents the sequence of characters currently
contained in the character array argument.
Program:
public class StrCon {
public static void main(String[] args) {
String a=new String();
System.out.println("Empty String"+a);
char ch[]={'a','b','c','d'};
String b=new String(ch);
System.out.println("String with one argument as Char="+b);
program:
public class A {
public static void main(String[] args) {
char ch[]={'a','b','c'};
String a=new String(ch);
System.out.println("String literals="+a);
String b="hello";
System.out.println("String literals="+b);
System.out.println("concatenation of string="+a+b);
int a1=10;
System.out.print("concatenation of string with other data type="+a1);
}
}
output:
String literals=abc
String literals=hello
concatenation of string=abchello
concatenation of string with other data type=10
5. Character Extraction:
The String class provides a no.of ways in which characters can be extracted from a String
object.
5.3 getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This method
is called getBytes( ), and it uses the default character-to-byte conversions provided by the
platform. Here is its simplest form:
byte[ ] getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when you
are exporting a String value into an environment that does not support 16-bit Unicode
characters.
program:
public class CO {
public static void main(String[] args) {
String a="hello";
String b="ELL";
System.out.println("region match="+a.regionMatches(1, b, 0, 2));
System.out.println("region match with IgnoreCase()="+a.regionMatches(true,1, b, 0, 2));
}
}
output:
region match=false
region match with IgnoreCase()=true
public class CO {
public static void main(String[] args) {
String a="hello";
String b="ELL";
System.out.println("Start with ="+a.startsWith("h"));
System.out.println("end with="+a.endsWith("llo"));
System.out.println("start with index ="+a.startsWith("llo",2));
}
}
output:
Start with =true
end with=true
start with index =true
Here, startIndex specifies the index at which point the search begins. For indexOf( ), the
search runs from startIndex to the end of the string. For lastIndexOf( ), the search runs from
startIndex to zero.
program:
public class CO {
public static void main(String[] args) {
String s1="hello hru";
System.out.println("indexof char="+s1.indexOf('e'));
System.out.println("indexof String="+s1.indexOf("hru"));
System.out.println("indexof char at start index="+s1.indexOf('e',1));
System.out.println("indexof String at start index="+s1.indexOf("hru",1));
System.out.println("lastindexof char="+s1.lastIndexOf('e'));
System.out.println("lastindexof string="+s1.lastIndexOf("ll"));
System.out.println("lastindex of char at start index="+s1.lastIndexOf('e',7));
System.out.println("lastindexof string at start="+s1.lastIndexOf("ell",7));
10.1 substring( )
You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a copy
of the substring that begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the beginning and ending
index of the substring:
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The
string returned contains all the characters from the beginning index, up to, but not
including, the ending index.
10.1 concat( )
You can concatenate two strings using concat( ), shown here:
String concat(String str)
This method creates a new object that contains the invoking string with the contents
of str appended to the end. concat( ) performs the same function as +.
program:
public class CO {
public static void main(String[] args) {
String s1="wel come to";
String s2=" cec";
System.out.println("Concatenation="+s1.concat(s2));
}}
output:
Concatenation=wel come to cec
10.3 replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character in
the invoking string with another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the character to be replaced by the character specified by replacement.
10.5 trim( )
The trim( ) method returns a copy of the invoking string from which any leading and trailing
whitespace has been removed. It has this general form:
String trim( )
Here is an example:
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
public class CO {
public static void main(String[] args) {
String s1=" wel come to cec ";
System.out.println("trim() ="+s1.trim());
program:
public class CO {
public static void main(String[] args) {
int a=10;
float b=10;
double c=10.0;
char d='a';
char e[]={'a','b','c'};
System.out.println("String.valueOf(int)="+String.valueOf(a));
System.out.println("String.valueOf(float)="+String.valueOf(b));
System.out.println("String.valueOf(double)="+String.valueOf(c));
System.out.println("String.valueOf(char)="+String.valueOf(d));
System.out.println("String.valueOf(char,index,index)="+String.valueOf(e,1,2));
}}
output:
String.valueOf(int)=10
Method Description
int codePointBefore(int i) Returns the Unicode code point at the index which precedes i.
int offsetByCodePoints(int start, Returns the index within the invoking string that is num
int num) codepoints beyond the starting index start.
boolean contains(CharSequence Returns true if the invoking object contains the String
str) specified by str, else it returnsfalse.
boolean Returns true if the invoking string contains the same String as
contentEquals(CharSequence str) str, else it returnsfalse.
boolean Returns true if the invoking string contains the same String as
contentEquals(StringBuffer str) str, else it returnsfalse.
static String format(Locale loc, Returns a String formatted as specified by fmtstr. Formatting
String fmtstr, Object... args) is specified by Locale loc.
String replaceFirst(String regExp, Returns a Stringin which first substring that matches with
String newStr) regExp is replaced by newStr.
String replaceAll(String regExp, Returns a Stringin which all the substrings that matches with
String newStr) regExp are replaced by newStr.
CharSequence subSequence(int Returns a substring of the invoking string that begins at start
start, int stop) and ends at stop.
program:
class CO
{
public static void main(String arg[])
{
String a = "Hello How are you?";
System.out.println("codepoint of element at index 0 : " + a.codePointAt(0));
System.out.println("code point of element before index 1 : " + a.codePointBefore(1));
System.out.println("Number of codePoints " + a.codePointCount(1, 4));
System.out.println("Checks if apple contains ppl : " + a.contains("how"));
System.out.println("ContentEquals checks : " + a.contentEquals("hello"));
System.out.println(" string patterns match : " + a.matches("how"));
System.out.println("Checks if the string is empty :" + " ".isEmpty());
System.out.println("Replaces the first with argument passed : " + a.replaceFirst("Hello",
"hello"));
System.out.println("ReplacesAll passed in the string : " + a.replaceAll("e", "E"));
}
}
output:
codepoint of element at index 0 : 72
code point of element before index 1 : 72
Number of codePoints 3
Checks if apple contains ppl : false
ContentEquals checks : false
string patterns match : false
13. StringBuffer:
StringBuffer class is used to create a mutable string object i.e its state can be changed
after it is created. It represents growable and writable character sequence. As we know
that String objects are immutable, so if we do a lot of changes with String objects, we
will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It
is also thread safe.
StringBuffer Constructors:
StringBuffer defines these four constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
StringBuffer()
1 This constructs a string buffer with no characters in it and an initial capacity of 16
characters.
StringBuffer(CharSequence seq)
2 This constructs a string buffer that contains the same characters as the specified
CharSequence.
StringBuffer(int capacity)
3
This constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
4
This constructs a string buffer initialized to the contents of the specified string.
program:
class CO
{
public static void main(String arg[])
{
StringBuffer a =new StringBuffer("hello");
System.out.println("Lenthg of stringbuffer: " + a.length());
System.out.println("capacity of stringBuffer : " + a.capacity());
}
}
output:
Lenthg of stringbuffer: 5
capacity of stringBuffer : 21
13.2 SetLength( )
To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form
is shown here:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative.
program:
public class CO {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("Hello");
char c[]=new char[buff.length()];
buff.getChars(1, 3, c, 0);
System.out.println(c);
13.5 append( ):
The append( ) method concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object. It has several overloaded versions. Here are a few
of its forms:
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( )
program:
public class CO {
public static void main(String[] args) {
StringBuffer buff = new StringBuffer("wel");
String a="come to cec at ";
int b=9;
String sb=buff.append(a).append(b).toString();
System.out.println("Append():"+sb);
}
}
output:
Append():welcome to cec at 9
program:
public class CO {
public static void main(String[] args) {
StringBuffer b = new StringBuffer("wel");
String a="come";
char c[]={'t','o'};
System.out.println("inser(String obj) :"+b.insert(1, a));
System.out.println("inser(char) :"+b.insert(1, c));
System.out.println("inser(String) :"+b.insert(1, "WEL"));
}
}
output:
inser(String obj) :wcomeel
inser(char) :wtocomeel
inser(String) :wWELtocomeel
13.7 reverse( ) :
We can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
This method returns the reversed object on which it was called
13. 9 replace( ) :
we can replace one set of characters with another set inside a StringBuffer object by calling
replace( ). Its signature is shown here:
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
program:
public class CO {
public static void main(String[] args) {
StringBuffer b = new StringBuffer("Hello");
System.out.println("Original String:"+b);
System.out.println("replace String:"+b.replace(0, 3, "HEL"));
}
}
output:
Original String:Hello
replace String:HELlo
13.10 substring( ) :
we can obtain a portion of a StringBuffer by calling substring( ). 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
program:
public class CO {
public static void main(String[] args) {
StringBuffer b = new StringBuffer("Hello");
System.out.println("Original String:"+b);
System.out.println("Sub String with index:"+b.substring(1));
System.out.println("Sub String with start index to end :"+b.substring(1, 3));
}
}
output:
Original String:Hello
Sub String with index:ello
Sub String with start index to end :el
Method Description
int codePointAt(int index)
Returns the character (Unicode code point) at the
specified index.
int codePointBefore(int index)
Returns the character (Unicode code point) before the
specified index.
int codePointCount(int Returns the number of Unicode code points in the
beginIndex, int endIndex) specified text range of this sequence.
int indexOf(String str)
Returns the index within this string of the first
occurrence of the specified substring.
Returns the index within this string of the first
int indexOf(String str, int
fromIndex) occurrence of the specified substring, starting at the
specified index.
int lastIndexOf(String str)
Returns the index within this string of the rightmost
occurrence of the specified substring.
int lastIndexOf(String str, int Returns the index within this string of the last
fromIndex) occurrence of the specified substring.
int offsetByCodePoints(int index, Returns the index within this sequence that is offset
int codePointOffset) from the given index by codePointOffset code
Program:
class CO
{
public static void main(String args[])
{
}
}
output:
Unicode = 97
Length 97
Substring Index = 0
Substring Index = -1
Reverse = egelloc gnireenoihnE aranaC