Module 2
Module 2
of ISE
Department of Information Science &
Engineering
Advance Java BIS402
Faculty: Sahibdeep Singh
Module 2- String Handling
STRING
object that represents sequence of
char values.
Present in a package called
Dept. of ISE java.lang.String
For example:
char[] ch={‘C’,’S’,’E’};
String s=new String(ch);
Is same as:
String s=“CSE”
String Constructors
1. String();
2. String(char chars[ ])
3. String(char chars[ ], int startIndex, int
Dept. of ISE
numChars)
4. String(byte asciiChars[ ])
5. String(byte asciiChars[ ], int startIndex,
int numChars)
String class supports several
constructors.
To create an empty String, we call the
default constructor.
Dept. of ISE For example,
String s = new String();
will create an instance of String with no
characters in it.
To create a String initialized by an array
of characters, use the constructor shown
here:
String(char chars[ ])
Dept. of ISE Here is an example:
char[] chars = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the
string “abc”.
•We can specify a subrange of a character array as
an initializer using the following constructor:
String(char chars[ ], int startIndex, int
numChars)
startIndex specifies the index at which the
subrange begins
Dept. of ISE
numChars specifies the number of
characters to use.
Example:
char[] chars = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
String class provides constructors that
class SubStringCons {
public static void main(String args[]) {
byte[] ascii = {65, 66, 67, 68, 69, 70 }; Output:
ABCDEF
String s1 = new String(ascii);
CDE
Dept. of ISE
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
How to create String object?
Dept. of ISE
String Literal
• For Example:
String s="welcome";
Dept. of ISE
String s1="Welcome";
String s2="Welcome“;
Dept. of ISE
Example:
String s=“ACIT"+“Engineering";
System.out.println(s);
Dept. of ISE
Output:
ACIT Engineering
Guess the answer
String s=50+30+“CSE"+40+40;
System.out.println(s);
Output:
80CSE4040
Dept. of ISE
Note: After a string literal, all the + will be
treated as string concatenation operator.
String Concatenation by concat()
Output:
Acharya Institute
Java toString() method
class Student{
int rollno;
String name;
String city;
Output:
Student@1fee6fc
Student@1eed786
Example of Java toString() method
class Student{
int rollno;
String name;
String city;
Dept. of ISE
public String toString()
{
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay",“Bengaluru");
System.out.println(s1);
System.out.println(s2);
}
}
Dept. of ISE
Character Extraction
Java String charAt()
Dept. of ISE
try{
str.getChars(6, 16, ch, 0);
System.out.println(ch);
}catch(Exception ex)
{ System.out.println(ex); }
}}
Example
ch[1]='b';
Dept. of ISE try{
str.getChars(6,10,ch,1);
System.out.println(ch);}
catch(Exception ex){ System.out.println(ex
); }
Example:
String str=new String("Hello Kumar how r u");
char[] ch=new char[10];
ch[0]='a';
Output:
ch[1]='b'; abKuma
K
try
Dept. of ISE {
str.getChars(6,10,ch,4);
System.out.println(ch);
System.out.println(ch[4]);
}catch(Exception ex)
{ System.out.println(ex); }
String getBytes()
String s1="ABCDEFG";
byte[] barr=s1.getBytes(); Output:
65
for(int i=0;i<barr.length;i++)
66
Dept. of ISE { 67
68
System.out.println(barr[i]); 69
70
} 71
String toCharArray
String s1="hello";
char[] ch=s1.toCharArray();
Output:
for(int i=0;i<ch.length;i++) { h
e
l
System.out.println(ch[i]); } l
o
Dept. of ISE
String Comparison
Dept. of ISE
There are three ways to compare string in
java:
By equals() method
Dept. of ISE By = = operator
By compareTo() method
1) String compare by equals()
String s1=“Kumar";
String s2=“Kumar";
String s3=new String(“Kumar");
String s4=“Atlas";
System.out.println(s1.equals(s2));
Dept. of ISE
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
Output
true
true
false
Example for equalsIgnoreCase
String s1=“Kumar";
String s2=“KUMAR";
System.out.println(s1.equals(s2))
System.out.println(s1.equalsIgnoreCase(s
Dept. of ISE 2));
Output:
false
true
Example for equals and equalsIgnoreCase
class equalsDemo {
public static void main(String args[]) Output:
Hello equals Hello -> true
{ Hello equals Good-bye -> false
String s1 = "Hello"; Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
Dept. of ISE
System.out.println(s1 + " equals " + s4 + " -> " +s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> "
+s1.equalsIgnoreCase(s4));
}
}
2) String compare by == operator
Dept. of ISE
Example for compare by == operator
class Teststringcomparison3{
public static void main(String args[]){
Output:
true
String s1=“Kumar"; false
String s2=“Kumar";
Dept. of ISE String s3=new String(“Kumaa");
System.out.println(s1==s2);
System.out.println(s1==s3);
} }
Example for equals() vs ==
Output:
Hello equals Hello ->
class Demo1 true
Hello == Hello ->
false
public static void main(String args[])
{
String s1 = "Hello";
Dept. of ISE String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -
> " +s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " +
(s1 == s2));
}}
3) String compare by compareTo() method
String s1="Sachin";
String s2="Sachin"; Output:
0
1
String s3="Ratan"; -1
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
Dept. of ISE
System.out.println(s3.compareTo(s1));
Example
Output:
• 0 because both are equal
String s1="hello"; • -5 because "h" is 5 times lower tha
n "m"
• -1 because "l" is 1 times lower than
String s2="hello"; "m"
• 2 because "h" is 2 times greater ”f"
String s3="mello";
String s4="hemlo";
Dept. of ISE
String s5="flag";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
System.out.println(s1.compareTo(s5));
Example
String s1="Sachin";
String s2="sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); Output:
-32
Dept. of ISE System.out.println(s1.compareTo(s3)); 1
-1
System.out.println(s3.compareTo(s1));
Java String compareTo(): empty string
{
String s1="hello";
Dept. of ISE String s2="";
String s3="me";
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s3));
}}
String startsWith
Output:
true
true
String endsWith
2 int indexOf(char ch, int startIndex) returns index position for the
given char value and from
index
Dept. of ISE
3 int indexOf(String substring) returns index position for the
given substring
System.out.println(index1+" "+index2);
Dept. of ISE int index3=s1.indexOf("is",4);
System.out.println(index3);
int index4=s1.indexOf('s');
System.out.println(index4);
Java String lastIndexOf
Output:
6
Example:
3
int index = str.lastIndexOf("of", 25); 19
-1
int endIndex)
Dept. of ISE
Example
String s="SachinTendulkar";
System.out.println(s.substring(6));
System.out.println(s.substring(0,6));
Dept. of ISE
Output:
Tendulkar
Sachin
String concat
Output:
java string
j ava string is immutable so assign it
explicitly
Replace()
• R e t urns a st ri ng re pl ac i ng al l t he o l d c har o r
CharSequence to new char or CharSequence.
• There are two type of replace methods in java string.
i. public String replace(char oldChar, char newChar)
Dept. of ISE ii. public String replac e(C harSeq uenc e target,
CharSequence replacement)
Example
Dept. of ISE
Output:
AIT is very good college
Java String replace(CharSequence target,
CharSequence replacement)
Output:
my name was ABC my name was college
String trim
Dept. of ISE
Example
Dept. of ISE
Output:
hello string java
hello stringjava
Example
Output:
22
hello java string
17
hello java string
ValueOf( ) method
double d = 123.45;
Dept. of ISE
String strDouble = String.valueOf(d);
char ch = 'A';
}
Changing the case of character within a string
Output:
acharya institute of technology
ACHARYA INSTITUTE OF TECHNOLOGY
Dept. of ISE
String Buffer
StringBuffer
Constructor Description
Dept. of ISE
Output:
Hello AIT
Example
sb.append("World ");
Output:
sb.append(2024); Hello World 2024
System.out.println(sb);`
Dept. of ISE
StringBuffer insert() method
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
Dept. of ISE System.out.println(sb);
Output:
} I like Java!
char[] c1 = new char[] {'Y','e','s'};
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.insert(6,c1);
System.out.println(sb3);
Output:
float f = 2.0f; Hello Yes World
Hello 2.0 World
StringBuffer sb5 = new StringBuffer("Hello World"); Hello My World
sb5.insert(6,f);
Dept. of ISE
System.out.println(sb5);
Object obj = new String("My");
StringBuffer sb8 = new StringBuffer("Hello World");
sb8.insert(6,obj);
System.out.println(sb8);
StringBuffer replace() method
endIndex.
Output:
Hellojavad
StringBuffer sb = new StringBuffer("progra
m compile time");
System.out.println("string: "+sb);
System.out.println("after replace: "
Dept. of ISE +sb.replace(8, 15, "run"));
Output:
string: program
compile time
after replace:
program run time
StringBuffer delete() method
beginIndex to endIndex.
endIndex)
Example
Dept. of ISE
Output:
Hlo
deleteCharAt( )
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a
test.");
Dept. of ISE sb.delete(4, 7);
System.out.println("After delete: " + sb); Output:
After delete: This a
sb.deleteCharAt(0); test.
After deleteCharAt:
his a test.
System.out.println("After deleteCharAt: " +
sb);
}}
StringBuffer reverse() method
re v e rse s t he c ha ra c t e rs w i t hi n a
StringBuffer object.
SringBuffer reverse( )
Dept. of ISE
Example
Dept. of ISE
Output:
olleH
capacity()
Example:
StringBuffer str = new StringBuffer();
Dept. of ISE
System.out.println( str.capacity() );
Output:
16
ensureCapacity()
Output:
34
length( ) and capacity( ):
general forms:
• int length( )
• int capacity()
Example
Output:
•Length of string AIT=3
Dept. of ISE
Differences
String StringBuffer
StringBuffer StringBuilder
StringBuilder is non-
StringBuffer is synchronized i.e.
synchronized i.e. not thread safe.
thread safe. It means two
Dept. of ISE It means two threads can call
threads can't call the methods of
the methods of StringBuilder
StringBuffer simultaneously.
simultaneously.