SlideShare a Scribd company logo
Programming in Java
Lecture 12: String Handling
By
Ravi Kant Sahu
Asst. Professor
Lovely Professional University, PunjabLovely Professional University, Punjab
Introduction
 Every string we create is actually an object of type String.
 String constants are actually String objects.
 Example:
System.out.println("This is a String, too");
 Objects of type String are immutable i.e. once a String object
is created, its contents cannot be altered.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
String
Constant
Why String is Immutable or Final?
 String has been widely used as parameter for many java classes e.g.
for opening network connection we can pass hostname and port
number as string ,
 we can pass database URL as string for opening database
connection,
 we can open any file in Java by passing name of file as argument to
File I/O classes.
 In case if String is not immutable , this would lead serious security
threat , means some one can access to any file for which he has
authorization and then can change the file name either deliberately
or accidentally and gain access of those file.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
 In java, four predefined classes are provided that either
represent strings or provide functionality to manipulate them.
Those classes are:
◦ String
◦ StringBuffer
◦ StringBuilder
◦ StringTokenizer
 String, StringBuffer, and StringBuilder classes are defined in
java.lang package and all are final.
 All three implement the CharSequence interface.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why String Handling?
String handling is required to perform following operations
on some string:
 compare two strings
 search for a substring
 concatenate two strings
 change the case of letters within a string
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Creating String objects
class StringDemo
{
public static void main(String args[])
{
String strOb1 = “Ravi";
String strOb2 = “LPU";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
String Class
String Constructor:
public String ()
public String (String)
public String (char [])
public String (byte [])
public String (char [], int offset, int no_of_chars)
public String (byte [], int offset, int no_of _bytes)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Examples
char [] a = {'c', 'o', 'n', 'g', 'r', 'a', 't', 's'};
byte [] b = {82, 65, 86, 73, 75, 65, 78, 84};
String s1 = new String (a); System.out.println(s1);
String s2 = new String (a, 1,5); System.out.println(s2);
String s3 = new String (s1); System.out.println(s3);
String s4 = new String (b); System.out.println(s4);
String s5 = new String (b, 4, 4); System.out.println(s5);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
String Concatenation
 Concatenating Strings:
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);
 Using concatenation to prevent long lines:
String longStr = “This could have been” +
“a very long line that would have” +
“wrapped around. But string”+
“concatenation prevents this.”;
System.out.println(longStr);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
String Concatenation with Other Data Types
 We can concatenate strings with other types of data.
Example:
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods of String class
 String Length:
length() returns the length of the string i.e. number of
characters.
int length()
Example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Character Extraction
 charAt(): used to obtain the character from the specified index
from a string.
public char charAt (int index);
Example:
char ch;
ch = "abc".charAt(1);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods Cont…
 getChars(): used to obtain set of characters from the string.
public void getChars(int start_index, int end_index, char[], int
offset)
Example: String s = “KAMAL”;
char b[] = new char [10];
b[0] = ‘N’; b[1] = ‘E’;
b[2] = ‘E’; b[3] = ‘L’;
s.getChars(0, 4, b, 4);
System.out.println(b);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods Cont…
 toCharArray(): returns a character array initialized by the
contents of the string.
public char [] toChar Array();
Example: String s = “India”;
char c[] = s.toCharArray();
for (int i=0; i<c.length; i++)
{
if (c[i]>= 65 && c[i]<=90)
c[i] += 32;
System.out.print(c[i]);
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
String Comparison
 equals(): used to compare two strings for equality.
Comparison is case-sensitive.
public boolean equals (Object str)
 equalsIgnoreCase( ): To perform a comparison that ignores case
differences.
Note:
 This method is defined in Object class and overridden in String class.
 equals(), in Object class, compares the value of reference not the content.
 In String class, equals method is overridden for content-wise comparison
of two strings.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
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));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> “
+s1.equalsIgnoreCase(s4));
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
String Comparison
 startsWith( ) and endsWith( ):
◦ The startsWith( ) method determines whether a given String
begins with a specified string.
◦ Conversely, endsWith( ) determines whether the String in
question ends with a specified string.
boolean startsWith(String str)
boolean endsWith(String str)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
String Comparison
compareTo( ):
 A string is less than another if it comes before the other in
dictionary order.
 A string is greater than another if it comes after the other in
dictionary order.
int compareTo(String str)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
class SortString {
static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Searching Strings
 The String class provides two methods that allow us to search a
string for a specified character or substring:
indexOf( ): Searches for the first occurrence of a character or
substring.
int indexOf(int ch)
lastIndexOf( ): Searches for the last occurrence of a character or
substring.
int lastIndexOf(int ch)
 To search for the first or last occurrence of a substring, use
int indexOf(String str)
int lastIndexOf(String str)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
 We can specify a starting point for the search using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
 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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +
"to come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " + s.indexOf('t'));
System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
System.out.println("indexOf(the) = " + s.indexOf("the"));
System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Modifying a String
 Because String objects are immutable, whenever we want to modify a
String, it will construct a new copy of the string with modifications.
 substring(): used to extract a part of a string.
public String substring (int start_index)
public String substring (int start_index, int end_index)
Example: String s = “ABCDEFG”;
String t = s.substring(2); System.out.println (t);
String u = s.substring (1, 4); System.out.println (u);
Note: Substring from start_index to end_index-1 will be returned.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
concat( ): used to concatenate two strings.
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 +.
Example:
String s1 = "one"; String s2 = s1.concat("two");
 It generates the same result as the following sequence:
String s1 = "one"; String s2 = s1 + "two";
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
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.
Example: String s = "Hello".replace('l', 'w');
 The second form of replace( ) replaces one character sequence with
another. It has this general form:
String replace(CharSequence original, CharSequence
replacement)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
trim( )
 The trim( ) method returns a copy of the invoking string from which
any leading and trailing whitespace has been removed.
String trim( )
Example:
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
Changing the Case of Characters Within a String
toLowerCase() & toUpperCase()
 Both methods return a String object that contains the
uppercase or lowercase equivalent of the invoking String.
String toLowerCase( )
String toUpperCase( )
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)

More Related Content

What's hot

Strings
StringsStrings
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
OUM SAOKOSAL
 
Java String
Java StringJava String
Java String
Java2Blog
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Edureka!
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
String in java
String in javaString in java
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
teach4uin
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
Akshay soni
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
Garuda Trainings
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
teach4uin
 
Lecture 7
Lecture 7Lecture 7
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Year
dezyneecole
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
İbrahim Kürce
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
Subhadra Sundar Chakraborty
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
Geetha Manohar
 
wrapper classes
wrapper classeswrapper classes
wrapper classes
Rajesh Roky
 

What's hot (20)

Strings
StringsStrings
Strings
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
Java String
Java StringJava String
Java String
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
String in java
String in javaString in java
String in java
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Generics
GenericsGenerics
Generics
 
Wrapper class (130240116056)
Wrapper class (130240116056)Wrapper class (130240116056)
Wrapper class (130240116056)
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Year
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIsOCA Java SE 8 Exam Chapter 3 Core Java APIs
OCA Java SE 8 Exam Chapter 3 Core Java APIs
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
wrapper classes
wrapper classeswrapper classes
wrapper classes
 

Viewers also liked

Java string handling
Java string handlingJava string handling
Java string handling
Salman Khan
 
Exception handling
Exception handlingException handling
Exception handling
Ravi Kant Sahu
 
Event handling
Event handlingEvent handling
Event handling
Ravi Kant Sahu
 
Multi threading
Multi threadingMulti threading
Multi threading
Ravi Kant Sahu
 
Packages
PackagesPackages
Packages
Ravi_Kant_Sahu
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
Ravi Kant Sahu
 
Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
Ravi_Kant_Sahu
 
Packages
PackagesPackages
Packages
Ravi Kant Sahu
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)
Ravi Kant Sahu
 
Internationalization
InternationalizationInternationalization
Internationalization
Ravi Kant Sahu
 
Concept of Object Oriented Programming
Concept of Object Oriented Programming Concept of Object Oriented Programming
Concept of Object Oriented Programming
Prognoz Technologies Pvt. Ltd.
 
Networking
NetworkingNetworking
Networking
Ravi Kant Sahu
 
Servlets
ServletsServlets
Servlets
Ravi Kant Sahu
 
April 2014
April 2014April 2014
April 2014
Siddharth Pereira
 
String handling in_java
String handling in_javaString handling in_java
String handling in_java
774474
 
Java Object Oriented Programming
Java Object Oriented Programming Java Object Oriented Programming
Java Object Oriented Programming
University of Potsdam
 
Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming
Prognoz Technologies Pvt. Ltd.
 
Open and Close Door ppt
 Open and Close Door ppt Open and Close Door ppt
Open and Close Door ppt
Devyani Vaidya
 
Array
ArrayArray

Viewers also liked (19)

Java string handling
Java string handlingJava string handling
Java string handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Event handling
Event handlingEvent handling
Event handling
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Packages
PackagesPackages
Packages
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
 
Packages
PackagesPackages
Packages
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)
 
Internationalization
InternationalizationInternationalization
Internationalization
 
Concept of Object Oriented Programming
Concept of Object Oriented Programming Concept of Object Oriented Programming
Concept of Object Oriented Programming
 
Networking
NetworkingNetworking
Networking
 
Servlets
ServletsServlets
Servlets
 
April 2014
April 2014April 2014
April 2014
 
String handling in_java
String handling in_javaString handling in_java
String handling in_java
 
Java Object Oriented Programming
Java Object Oriented Programming Java Object Oriented Programming
Java Object Oriented Programming
 
Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming Interesting Concept of Object Oriented Programming
Interesting Concept of Object Oriented Programming
 
Open and Close Door ppt
 Open and Close Door ppt Open and Close Door ppt
Open and Close Door ppt
 
Array
ArrayArray
Array
 

Similar to String handling(string class)

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
Ravi_Kant_Sahu
 
8. String
8. String8. String
8. String
Nilesh Dalvi
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
Gina Bullock
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
Gina Bullock
 
07slide
07slide07slide
07slide
Aboudi Sabbah
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
Ravi_Kant_Sahu
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
Infoviaan Technologies
 
Strings in java
Strings in javaStrings in java
Strings in java
Kuppusamy P
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
Sardar Alam
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
String Operations.pptx
String Operations.pptxString Operations.pptx
String Operations.pptx
pateljay401233
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .ppt
zainiiqbal761
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
Collection framework
Collection frameworkCollection framework
Collection framework
Ravi_Kant_Sahu
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10
mlrbrown
 
M C6java7
M C6java7M C6java7
M C6java7
mbruggen
 

Similar to String handling(string class) (20)

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
8. String
8. String8. String
8. String
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
 
Eo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5eEo gaddis java_chapter_08_5e
Eo gaddis java_chapter_08_5e
 
07slide
07slide07slide
07slide
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Strings in java
Strings in javaStrings in java
Strings in java
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
 
String Operations.pptx
String Operations.pptxString Operations.pptx
String Operations.pptx
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .ppt
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10
 
M C6java7
M C6java7M C6java7
M C6java7
 

Recently uploaded

The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
greendigital
 
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
0md20cgg
 
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptxFrom Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
Swing Street Radio
 
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
9u08k0x
 
DIGIDEVTV A New area of OTT Distribution
DIGIDEVTV  A New area of OTT DistributionDIGIDEVTV  A New area of OTT Distribution
DIGIDEVTV A New area of OTT Distribution
joeqsm
 
The Enigmatic Portrait, In the heart of a sleepy town
The Enigmatic Portrait, In the heart of a sleepy townThe Enigmatic Portrait, In the heart of a sleepy town
The Enigmatic Portrait, In the heart of a sleepy town
John Emmett
 
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and InspirationOrpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
greendigital
 
原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样
原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样
原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样
mul1kv5w
 
Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __
catcabrera
 
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting SagaThe Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
greendigital
 
Christian Louboutin: Innovating with Red Soles
Christian Louboutin: Innovating with Red SolesChristian Louboutin: Innovating with Red Soles
Christian Louboutin: Innovating with Red Soles
get joys
 
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdfUnveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
kenid14983
 
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and SafetyModern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
AITIX LLC
 
Leonardo DiCaprio House: A Journey Through His Extravagant Real Estate Portfolio
Leonardo DiCaprio House: A Journey Through His Extravagant Real Estate PortfolioLeonardo DiCaprio House: A Journey Through His Extravagant Real Estate Portfolio
Leonardo DiCaprio House: A Journey Through His Extravagant Real Estate Portfolio
greendigital
 
From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28
get joys
 
Emcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdfEmcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdf
subran
 
The Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling cityThe Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling city
John Emmett
 
Top IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdfTop IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdf
Xtreame HDTV
 
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
9u08k0x
 
Everything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdfEverything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdf
Xtreame HDTV
 

Recently uploaded (20)

The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
The Evolution of the Leonardo DiCaprio Haircut: A Journey Through Style and C...
 
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
定制(uow毕业证书)卧龙岗大学毕业证文凭学位证书原版一模一样
 
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptxFrom Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
From Swing Music to Big Band Fame_ 5 Iconic Artists.pptx
 
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
哪里买(osu毕业证书)美国俄勒冈州立大学毕业证双学位证书原版一模一样
 
DIGIDEVTV A New area of OTT Distribution
DIGIDEVTV  A New area of OTT DistributionDIGIDEVTV  A New area of OTT Distribution
DIGIDEVTV A New area of OTT Distribution
 
The Enigmatic Portrait, In the heart of a sleepy town
The Enigmatic Portrait, In the heart of a sleepy townThe Enigmatic Portrait, In the heart of a sleepy town
The Enigmatic Portrait, In the heart of a sleepy town
 
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and InspirationOrpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
Orpah Winfrey Dwayne Johnson: Titans of Influence and Inspiration
 
原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样
原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样
原版制作(Mercer毕业证书)摩斯大学毕业证在读证明一模一样
 
Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __Snoopy boards the big bow wow musical __
Snoopy boards the big bow wow musical __
 
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting SagaThe Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
The Unbelievable Tale of Dwayne Johnson Kidnapping: A Riveting Saga
 
Christian Louboutin: Innovating with Red Soles
Christian Louboutin: Innovating with Red SolesChristian Louboutin: Innovating with Red Soles
Christian Louboutin: Innovating with Red Soles
 
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdfUnveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
Unveiling Paul Haggis Shaping Cinema Through Diversity. .pdf
 
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and SafetyModern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
Modern Radio Frequency Access Control Systems: The Key to Efficiency and Safety
 
Leonardo DiCaprio House: A Journey Through His Extravagant Real Estate Portfolio
Leonardo DiCaprio House: A Journey Through His Extravagant Real Estate PortfolioLeonardo DiCaprio House: A Journey Through His Extravagant Real Estate Portfolio
Leonardo DiCaprio House: A Journey Through His Extravagant Real Estate Portfolio
 
From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28From Teacher to OnlyFans: Brianna Coppage's Story at 28
From Teacher to OnlyFans: Brianna Coppage's Story at 28
 
Emcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdfEmcee Profile_ Subbu from Bangalore .pdf
Emcee Profile_ Subbu from Bangalore .pdf
 
The Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling cityThe Gallery of Shadows, In the heart of a bustling city
The Gallery of Shadows, In the heart of a bustling city
 
Top IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdfTop IPTV UK Providers of A Comprehensive Review.pdf
Top IPTV UK Providers of A Comprehensive Review.pdf
 
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
高仿(nyu毕业证书)美国纽约大学毕业证文凭毕业证原版一模一样
 
Everything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdfEverything You Need to Know About IPTV Ireland.pdf
Everything You Need to Know About IPTV Ireland.pdf
 

String handling(string class)

  • 1. Programming in Java Lecture 12: String Handling By Ravi Kant Sahu Asst. Professor Lovely Professional University, PunjabLovely Professional University, Punjab
  • 2. Introduction  Every string we create is actually an object of type String.  String constants are actually String objects.  Example: System.out.println("This is a String, too");  Objects of type String are immutable i.e. once a String object is created, its contents cannot be altered. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) String Constant
  • 3. Why String is Immutable or Final?  String has been widely used as parameter for many java classes e.g. for opening network connection we can pass hostname and port number as string ,  we can pass database URL as string for opening database connection,  we can open any file in Java by passing name of file as argument to File I/O classes.  In case if String is not immutable , this would lead serious security threat , means some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Introduction  In java, four predefined classes are provided that either represent strings or provide functionality to manipulate them. Those classes are: ◦ String ◦ StringBuffer ◦ StringBuilder ◦ StringTokenizer  String, StringBuffer, and StringBuilder classes are defined in java.lang package and all are final.  All three implement the CharSequence interface. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Why String Handling? String handling is required to perform following operations on some string:  compare two strings  search for a substring  concatenate two strings  change the case of letters within a string Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Creating String objects class StringDemo { public static void main(String args[]) { String strOb1 = “Ravi"; String strOb2 = “LPU"; String strOb3 = strOb1 + " and " + strOb2; System.out.println(strOb1); System.out.println(strOb2); System.out.println(strOb3); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. String Class String Constructor: public String () public String (String) public String (char []) public String (byte []) public String (char [], int offset, int no_of_chars) public String (byte [], int offset, int no_of _bytes) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. Examples char [] a = {'c', 'o', 'n', 'g', 'r', 'a', 't', 's'}; byte [] b = {82, 65, 86, 73, 75, 65, 78, 84}; String s1 = new String (a); System.out.println(s1); String s2 = new String (a, 1,5); System.out.println(s2); String s3 = new String (s1); System.out.println(s3); String s4 = new String (b); System.out.println(s4); String s5 = new String (b, 4, 4); System.out.println(s5); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. String Concatenation  Concatenating Strings: String age = "9"; String s = "He is " + age + " years old."; System.out.println(s);  Using concatenation to prevent long lines: String longStr = “This could have been” + “a very long line that would have” + “wrapped around. But string”+ “concatenation prevents this.”; System.out.println(longStr); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. String Concatenation with Other Data Types  We can concatenate strings with other types of data. Example: int age = 9; String s = "He is " + age + " years old."; System.out.println(s); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Methods of String class  String Length: length() returns the length of the string i.e. number of characters. int length() Example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length()); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. Character Extraction  charAt(): used to obtain the character from the specified index from a string. public char charAt (int index); Example: char ch; ch = "abc".charAt(1); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. Methods Cont…  getChars(): used to obtain set of characters from the string. public void getChars(int start_index, int end_index, char[], int offset) Example: String s = “KAMAL”; char b[] = new char [10]; b[0] = ‘N’; b[1] = ‘E’; b[2] = ‘E’; b[3] = ‘L’; s.getChars(0, 4, b, 4); System.out.println(b); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. Methods Cont…  toCharArray(): returns a character array initialized by the contents of the string. public char [] toChar Array(); Example: String s = “India”; char c[] = s.toCharArray(); for (int i=0; i<c.length; i++) { if (c[i]>= 65 && c[i]<=90) c[i] += 32; System.out.print(c[i]); } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. String Comparison  equals(): used to compare two strings for equality. Comparison is case-sensitive. public boolean equals (Object str)  equalsIgnoreCase( ): To perform a comparison that ignores case differences. Note:  This method is defined in Object class and overridden in String class.  equals(), in Object class, compares the value of reference not the content.  In String class, equals method is overridden for content-wise comparison of two strings. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. Example class equalsDemo { public static void main(String args[]) { String s1 = "Hello"; 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)); System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> “ +s1.equalsIgnoreCase(s4)); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. String Comparison  startsWith( ) and endsWith( ): ◦ The startsWith( ) method determines whether a given String begins with a specified string. ◦ Conversely, endsWith( ) determines whether the String in question ends with a specified string. boolean startsWith(String str) boolean endsWith(String str) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. String Comparison compareTo( ):  A string is less than another if it comes before the other in dictionary order.  A string is greater than another if it comes after the other in dictionary order. int compareTo(String str) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. Example class SortString { static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "their", "country"}; public static void main(String args[]) { for(int j = 0; j < arr.length; j++) { for(int i = j + 1; i < arr.length; i++) { if(arr[i].compareTo(arr[j]) < 0) { String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. Searching Strings  The String class provides two methods that allow us to search a string for a specified character or substring: indexOf( ): Searches for the first occurrence of a character or substring. int indexOf(int ch) lastIndexOf( ): Searches for the last occurrence of a character or substring. int lastIndexOf(int ch)  To search for the first or last occurrence of a substring, use int indexOf(String str) int lastIndexOf(String str) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21.  We can specify a starting point for the search using these forms: int indexOf(int ch, int startIndex) int lastIndexOf(int ch, int startIndex) int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex)  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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. Example class indexOfDemo { public static void main(String args[]) { String s = "Now is the time for all good men " + "to come to the aid of their country."; System.out.println(s); System.out.println("indexOf(t) = " + s.indexOf('t')); System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t')); System.out.println("indexOf(the) = " + s.indexOf("the")); System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the")); System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10)); System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60)); System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10)); System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60)); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. Modifying a String  Because String objects are immutable, whenever we want to modify a String, it will construct a new copy of the string with modifications.  substring(): used to extract a part of a string. public String substring (int start_index) public String substring (int start_index, int end_index) Example: String s = “ABCDEFG”; String t = s.substring(2); System.out.println (t); String u = s.substring (1, 4); System.out.println (u); Note: Substring from start_index to end_index-1 will be returned. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. concat( ): used to concatenate two strings. 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 +. Example: String s1 = "one"; String s2 = s1.concat("two");  It generates the same result as the following sequence: String s1 = "one"; String s2 = s1 + "two"; Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
  • 25. 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. Example: String s = "Hello".replace('l', 'w');  The second form of replace( ) replaces one character sequence with another. It has this general form: String replace(CharSequence original, CharSequence replacement) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
  • 26. trim( )  The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. String trim( ) Example: String s = " Hello World ".trim(); This puts the string “Hello World” into s. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
  • 27. Changing the Case of Characters Within a String toLowerCase() & toUpperCase()  Both methods return a String object that contains the uppercase or lowercase equivalent of the invoking String. String toLowerCase( ) String toUpperCase( ) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab
  • 28. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)