(c) D. R.
Gangodkar
Java Provides a Class named String to create
strings.
This class has various methods to:
(c) D. R. Gangodkar
(c) D. R. Gangodkar
String class has several constructors as below:
Create a String with characters
String s= new String (“This is a new String”);
(c) D. R. Gangodkar
(c) D. R. Gangodkar
Write a Program to demonstrate the String creation
class MakeString
{
public static void main(String args[ ])
{
char c[ ] = {'J', 'a', 'v', 'a'};
String s1 = new String(c); //Create a string using char array
String s2 = new String(s1);
[Link](s1);
[Link](s2);
}
} (c) D. R. Gangodkar
• Write Java statements to print length (number of
chars held by a String 0bject)
• This can be obtained using length() method of String
class as shown below:
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
We now understand how do we extract the characters
from String object
String class has following methods for char extraction
We discuss each of these…
(c) D. R. Gangodkar
How to extract a single char from String ?
e.g. ‘b’ from “abcd”?
Make use of
String s1=new String(“abcd”);
char ch1 =[Link](2);//Assigns c to ch1
Similarly:
(c) D. R. Gangodkar
Consider a String "This is a demo of a String method.”
Write a Program to extract “demo” from this String
Make use of a method getChars method of a
String class which is explained next….
(c) D. R. Gangodkar
: Extracts Multiple consecutive
characters from String object
void getChars(int sourceStart, int sourceEnd,
char[ ] target, int targetStart)
sourceStart – specifies the index of the beginning of the
substring
sourceEnd – specifies an index that is one past the end
of the desired subString
target – is the array that will receive the characters
targetStart – is the index within target at which the
subString will be copied is passed in this
parameter
Lets see an example..
(c) D. R. Gangodkar
Consider "This is a demo of of a String method.”
How can we copy “demo” into a character Array
String s = "This is a demo of the of a String method.";//38 chars
int startIndex = 10;//Specifies the index of first char
int endIndex = 14;//One more than the last char index
char buf[ ] = new char[4];//For storing char
[Link]( startIndex , endIndex, buf, 0);
[Link](buf);
What will the output??
(c) D. R. Gangodkar
demo
(c) D. R. Gangodkar
Problem statement:
Consider a string "This is a demo of a String methods";
Extract all the characters from the string object and store them
into a character Array.
(c) D. R. Gangodkar
Returns all the characters of a String object. Need to
store in char array.
Example:
String s = “This is a demo of a String methods";
char charAry[ ]; //Array Declared
charAry=[Link](); //Array Created and initialized
[Link](charAry); //char array can be printed
(c) D. R. Gangodkar
The String class includes several methods that compare
strings or substrings within strings
We discuss each of these
(c) D. R. Gangodkar
• It is not enough to know that two Strings are
identical. You need to know which is less than, equal
to, or greater than the other.
• What is meant by > , <, == ?
• A string is less than the another if it comes before
the other in the dictionary order.
• A string is greater than the another if it comes after
the other in the dictionary order.
• The String method compareTo() serves this
purpose.
(c) D. R. Gangodkar
General form:
int compareTo(String str)//Case sensitive
int compareToIgnoreCase (String str)
can be used for checking ignoring case
The result of the comparison is returned and is
interpreted as shown here:
(c) D. R. Gangodkar
Lets see an example
(c) D. R. Gangodkar
Write a Program to compare two strings ( case
sensitive and ignoring the case)
• Entire content is compared
(c) D. R. Gangodkar
class equalsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";//ALL caps
[Link]([Link](s2));
[Link]([Link](s3));
[Link]([Link](s4));
[Link]([Link](s4));
}
}
(c) D. R. Gangodkar
Consider two strings given below:
• My name is Rahul
• My name is Amit
Write a program to check if the part of the
strings are same (case sensitive and case
insensitive)
In the above example “My name is” is same in both the
strings
(c) D. R. Gangodkar
Can be done using regionMatches() method of
String class
startindex – index of character in str1,
str2- object to be compared
str2startindex - – index of character in str2
numChars – number of characters to be compared
ignoring the case of characters
Lets see the program in the next slide…
(c) D. R. Gangodkar
startindex – index of character in str1,
str2- object to be compared
str2startindex - – index of character in str2
numChars – number of characters to be compared
Lets write the Program statements:
String str1= new String (“My name is Rahul”);
String str2= new String (“ My name is Amit”);
boolean compare=[Link](0, str2, 0, 10);
[Link](compare);
(c) D. R. Gangodkar
(c) D. R. Gangodkar
1) equals() method compares the characters inside a
String object.
2) == operator compares two object references to see
whether they refer to the same instance
Lets see an example:
Write a program to compare contents to two string
objects
(c) D. R. Gangodkar
class EqualsNotEqualTo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = new String(s1);
[Link]([Link](s2));//TRUE
[Link]((s1 == s2));//False
}
}
(c) D. R. Gangodkar
Some discussion on String comparison
String can be created using String literals:
String s = “Rahul";
String s2 = “Rahul";
[Link](s == s2); // true
However this method of comparison should be avoided
Use
boolean b=[Link](s2)
(c) D. R. Gangodkar
Using the constructor of String Class
String s1=new String (“abc”); //Object 1
String s2=new String (“abc”); //Object 2
Separate memory allocated for each object.
boolean b=[Link](s2)
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
Methods like following do not change the original String object
but they return the new object by constructing a new String.
1) subString(n,m)
2) concat(s2)
3) replace(‘x,’y’)
4) trim()
(c) D. R. Gangodkar
Problem Statement (HackerRank)
(NetBeans helloworld/StringSubString)
Given a String
• extract the substrings of length “k”, where k is an int
• order them in Lexicographical order and
• Print the first and last substring
Explanation as below..
(c) D. R. Gangodkar
Lets understand the steps involved
• Read the string and size of sub string from
the user
• Extract all possible sub strings from given
string
• Order them Lexicographically (sort)
• Print the first and last substring
(c) D. R. Gangodkar
import [Link].*; //Scanner class
class TestClass
{
{
public static void main (String args[ ])
{
//Read String and size of sub string
Scanner sc=new Scanner( [Link] );
[Link]( "Enter the string“ );
String input= [Link]();
[Link]("Enter size of substring");
int subSize=[Link]();
(c) D. R. Gangodkar
/* Extract substrings based on value of subSize
We do not know how many sub strings would be
generated */
String concat=“ "; //Create concatenated string
int i=0; // Value of i provides no. of sub strings
for ( i=0; i<=[Link]() - subSize; i++)
{ //extract sub string from i, to subSize
//Use conact to create the sub strings separated with
space
concat+= [Link](i, subSize +i )+ " ";
//NOTE: here “ “ is a separator
}
(c) D. R. Gangodkar
// Copy substrings from concat to String array
String sArray[ ]=new String [ i ]; // i provided no. of substrings
// Scanner extracts substrings (token) based on “ “ as separator
Scanner scStr=new Scanner( concat );
int j=0;
while( [Link]() ) //are there more tokens
{
sArray[ j ++] =[Link](); //extract token
}
(c) D. R. Gangodkar
//Sort the array Lexicographically. i provides no. of substrings
for(int k = 0; k < i-1; ++k)
{
for (int l = k + 1; l < i; ++l)
{
if (sArray[k].compareTo(sArray[l]) > 0)
{
String temp = sArray[k];
sArray[k] = sArray[l];
sArray[l] = temp;
}
}
}
// Print the first and last substring
[Link](sArray[0]+ " "+sArray[i-1]);
} //end of main
} //end of class (c) D. R. Gangodkar
Lets Achieve the same using Java library classes
import [Link].*; //SortedSet and TreeSet classes
class SubStr
{
public static void main(String[ ] args)
{
Scanner scan=new Scanner([Link]);
String str=[Link]();
int k=[Link]();
SortedSet<String> sets=new TreeSet<String> ();
for(int i=0; i<=[Link]()-k; i++)
{
[Link]( [Link] (i, i+k) );
}
[Link]([Link]());
[Link]([Link]());
}//end of main
} //end of class (c) D. R. Gangodkar
• Write a program to print all the
• Uppercase,
• Lower Case and
• digits present in the given string
e.g. “My Address is 566/6, Bell Road”
One of the important wrapper class is Character in
[Link] package.
• which has various static methods that help in understand
the String object,
Lets see the various methods….
(c) D. R. Gangodkar
String str1=new String("My Address is 566/6, Bell Road");
//Check each char for letter or digit
char c=[Link](0);
boolean b=[Link](c);//Letter or not?
//If true then check is it upper or lower
boolean b=[Link](c); //or
//Similarly…
c=[Link](1);
b=[Link](c);
[Link](b);
//Check for digit
c=[Link](14);
b=[Link](c);
[Link](b);
//Neither letter nor digit means special char…
(c) D. R. Gangodkar
• Can we concatenate the objects with string?
• We can !! We need to add the “toString()”
method ( that converts instance variables to
String) to the class
• This method automatically gets invoked while
concatenation.
• We can add the following method to the Class
Box that we have seen:
public String toString() //Method returns string
{
return "Dimensions are " + width + " by " + depth + " by "
+ height + ".";
}
As shown in the next slide:
(c) D. R. Gangodkar
(c) D. R. Gangodkar
(c) D. R. Gangodkar
class toStringDemo
{
public static void main(String args[ ])
{
Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
[Link](b); // convert Box to string
[Link](s);
}
} What is the output??
Dimensions are 10.0 by 30.0 by 20.0.
Box b: Dimensions are 10.0 by 30.0 by 20.0.
(c) D. R. Gangodkar
If we do not include the “toString()” method in
Box class, then what will be printed.
[Link]@9931f5 // This is the Object ID
Box b: [Link]@9931f5
Note:
1. Since all the Classes are sub-classes of “Object”
class, of API, the toString() of Object is invoked.
toString() constructs the object id as:
getClass().getName() + '@' + [Link](hashCode())
(c) D. R. Gangodkar
(c) D. R. Gangodkar
3) StringBuffer(String str) – accepts a String argument that
initially sets the content of the StringBuffer Object and
reserves room for 16 more characters without reallocation.
(c) D. R. Gangodkar
• Current length of a StringBuffer can be found via the length()
method, while the total allocated capacity can be found
through the capacity() method.
Lets see the example
(c) D. R. Gangodkar
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer = " + sb);
[Link]("length = " + [Link]());
[Link]("capacity = " + [Link]());
}
}// The output will be :
buffer = Hello
length = 5
capacity = 21
(c) D. R. Gangodkar
if you know in advance that you will be appending a
large number of small strings to a StringBuffer
• Use ensureCapacity() to allocate more memory
void ensureCapacity(int minimumCapacity)
After using the above method, the new capacity is the
larger of
• The minimumCapacity argument and Twice the old
capacity, plus 2.
StringBuffer s1=new StringBuffer(); StringBuffer s1=new StringBuffer();
[Link]([Link]());//16 [Link]([Link]());//16
[Link](37); [Link](17);//less than 34
[Link]([Link]());//37 [Link]([Link]());//34
16*2+2=34
(c) D. R. Gangodkar
void setLength(int newLength)
Sets the length of this String buffer.
Lets see an example to understand the difference
between setLength() and ensureCapacity()
StringBuffer buf = new StringBuffer("0123456789");//10
char +16
[Link](5); // buf now contains "01234"
[Link](10); // buf now contains "01234"
followed
by five null
characters
Note: However in this case the capacity is still
26 (c) D. R. Gangodkar
(c) D. R. Gangodkar
Example:
int a = 42;
StringBuffer sb = new StringBuffer(40);
String s = [Link]("a = ").append(a).append("!").toString();
[Link](s);
Output: a = 42!
Note: When stored chars exceeds the capacity, capacity it is
increased to (old capacity*2)+2
(c) D. R. Gangodkar
Here, index specifies the index at which point the String will
be inserted into the invoking StringBuffer object.
Example:
StringBuffer sb = new StringBuffer("I Java!");
[Link](2, "like ");
[Link](sb);
(c) D. R. Gangodkar
Example:
StringBuffer s = new StringBuffer("abcdef");
[Link](s);
[Link]();
[Link](s);//Output fedcba
(c) D. R. Gangodkar
(c) D. R. Gangodkar
Exercise
1. What is the length and capacity of the following :
StringBuffer sb = new StringBuffer("Able was I ere I saw Elba.");
2. Consider the following string:
String hannah = "Did Hannah see bees? Hannah did.";
What is the value returned by the method call [Link](12)?
3. Show two ways to concatenate the following two strings
together to get the string "Hi, mom.":
String hi = "Hi, ";
String mom = "mom.";
(c) D. R. Gangodkar
Output Formatting:
• Basic formatting can be achieved using PrintStream object.
“[Link]” as follows
int i = 461012;
[Link]("The value of i is: %d%n", i); //%n is newline
Double d= 3.142567745;
[Link](“Value of d is: %.3f%n", d); //3 decimal digits
Customized formatting can be done using class
[Link] as given below:
DecimalFormat nf1 = new DecimalFormat("00000E00");
String f1 = [Link](1187654.321);
[Link](f1);//Output 11877E02 More? Homework
(c) D. R. Gangodkar
Wrapper Classes:
Wrapper classes convert the primitive data types into objects.
Integer, Double, Float, Character, Boolean, Byte, Short etc..
Helps in Storing and retrieving using Java API classes like
“Stack”
[Link](a);//Converting int a to String object
[Link](str);//Converting string str to long
[Link](str);//Converts string to double object
We look at an example that makes use of Stack class.
(c) D. R. Gangodkar
Stack class can be used for storing objects including that of user classes
import [Link];
class StackTest
{
public static void main(String[] args) throws Exception
{
Stack<Integer> mystack=new Stack<Integer>();
Integer iObj=new Integer(10);
[Link](iObj);//Stores object
[Link](20);//AutoBoxing
int sum=[Link]()+[Link]();//Unboxing (peek)
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());//Runtime error EmptyStack
}
}
(c) D. R. Gangodkar