SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Programming in Java
Lecture 12: String Handling
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.
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.
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 of them implement the CharSequence interface.
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
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);
}
}
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)
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);
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);
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);
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());
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";
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);
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);
Methods Cont…
• toCharArray(): returns a character array initialized by the contents
of the string.
public char [] toCharArray();
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]);
}
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.
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));
}
}
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)
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)
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]);
}
}
}
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)
• 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.
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));
}
}
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.
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)
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.
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( )
L13 string handling(string class)

Weitere ähnliche Inhalte

Was ist angesagt?

ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVASAGARDAVE29
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and OperatorsMarwa Ali Eissa
 
Java String
Java StringJava String
Java StringJava2Blog
 
SQL Queries
SQL QueriesSQL Queries
SQL QueriesNilt1234
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
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
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 

Was ist angesagt? (20)

ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
String in java
String in javaString in java
String in java
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Java String
Java StringJava String
Java String
 
Java Strings
Java StringsJava Strings
Java Strings
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java threads
Java threadsJava threads
Java threads
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Java String class
Java String classJava String class
Java String class
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Andere mochten auch

Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packagesSardar Alam
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
Indian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It WorksIndian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It Worksbuzzfactory
 
String java
String javaString java
String java774474
 
Open and Close Door ppt
 Open and Close Door ppt Open and Close Door ppt
Open and Close Door pptDevyani Vaidya
 
ITFT- Applet in java
ITFT- Applet in javaITFT- Applet in java
ITFT- Applet in javaAtul Sehdev
 
L18 applets
L18 appletsL18 applets
L18 appletsteach4uin
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java AppletsTareq Hasan
 

Andere mochten auch (17)

Strings
StringsStrings
Strings
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
Indian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It WorksIndian Property Lawyers .com - How It Works
Indian Property Lawyers .com - How It Works
 
String java
String javaString java
String java
 
April 2014
April 2014April 2014
April 2014
 
Open and Close Door ppt
 Open and Close Door ppt Open and Close Door ppt
Open and Close Door ppt
 
java Applet Introduction
java Applet Introductionjava Applet Introduction
java Applet Introduction
 
Java Applet
Java AppletJava Applet
Java Applet
 
applet using java
applet using javaapplet using java
applet using java
 
ITFT- Applet in java
ITFT- Applet in javaITFT- Applet in java
ITFT- Applet in java
 
Java applet
Java appletJava applet
Java applet
 
L18 applets
L18 appletsL18 applets
L18 applets
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Java Applet
Java AppletJava Applet
Java Applet
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java Applets
 

Ähnlich wie L13 string handling(string class)

String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
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
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptxadityaraj7711
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptxAnkurRajSingh2
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi_Kant_Sahu
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Featurexcoda
 
Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_KarthicaMarasamy
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTSasideepa
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTSasideepa
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdfssusere19c741
 
CP-STRING (1).ppt
CP-STRING (1).pptCP-STRING (1).ppt
CP-STRING (1).pptmounikanarra3
 

Ähnlich wie L13 string handling(string class) (20)

Java string handling
Java string handlingJava string handling
Java string handling
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
L14 string handling(string buffer class)
L14 string handling(string buffer class)L14 string handling(string buffer class)
L14 string handling(string buffer class)
 
Programing with java for begniers .pptx
Programing with java for begniers  .pptxPrograming with java for begniers  .pptx
Programing with java for begniers .pptx
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
07slide
07slide07slide
07slide
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Team 1
Team 1Team 1
Team 1
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
 
Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_Presentation more c_programmingcharacter_and_string_handling_
Presentation more c_programmingcharacter_and_string_handling_
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
CP-STRING (1).ppt
CP-STRING (1).pptCP-STRING (1).ppt
CP-STRING (1).ppt
 

Mehr von teach4uin

Controls
ControlsControls
Controlsteach4uin
 
validation
validationvalidation
validationteach4uin
 
validation
validationvalidation
validationteach4uin
 
Master pages
Master pagesMaster pages
Master pagesteach4uin
 
.Net framework
.Net framework.Net framework
.Net frameworkteach4uin
 
Scripting languages
Scripting languagesScripting languages
Scripting languagesteach4uin
 
Code model
Code modelCode model
Code modelteach4uin
 
Asp db
Asp dbAsp db
Asp dbteach4uin
 
State management
State managementState management
State managementteach4uin
 
security configuration
security configurationsecurity configuration
security configurationteach4uin
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tagsteach4uin
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tagsteach4uin
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentationteach4uin
 
.Net overview
.Net overview.Net overview
.Net overviewteach4uin
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lessonteach4uin
 
memory
memorymemory
memoryteach4uin
 
storage clas
storage classtorage clas
storage clasteach4uin
 

Mehr von teach4uin (20)

Controls
ControlsControls
Controls
 
validation
validationvalidation
validation
 
validation
validationvalidation
validation
 
Master pages
Master pagesMaster pages
Master pages
 
.Net framework
.Net framework.Net framework
.Net framework
 
Scripting languages
Scripting languagesScripting languages
Scripting languages
 
Css1
Css1Css1
Css1
 
Code model
Code modelCode model
Code model
 
Asp db
Asp dbAsp db
Asp db
 
State management
State managementState management
State management
 
security configuration
security configurationsecurity configuration
security configuration
 
static dynamic html tags
 static dynamic html tags static dynamic html tags
static dynamic html tags
 
static dynamic html tags
static dynamic html tagsstatic dynamic html tags
static dynamic html tags
 
New microsoft office power point presentation
New microsoft office power point presentationNew microsoft office power point presentation
New microsoft office power point presentation
 
.Net overview
.Net overview.Net overview
.Net overview
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
enums
enumsenums
enums
 
memory
memorymemory
memory
 
array
arrayarray
array
 
storage clas
storage classtorage clas
storage clas
 

KĂźrzlich hochgeladen

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

KĂźrzlich hochgeladen (20)

Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

L13 string handling(string class)

  • 1. Programming in Java Lecture 12: String Handling
  • 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. 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.
  • 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 of them implement the CharSequence interface.
  • 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
  • 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); } }
  • 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)
  • 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);
  • 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);
  • 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);
  • 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());
  • 12. 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";
  • 13. 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);
  • 14. 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);
  • 15. Methods Cont… • toCharArray(): returns a character array initialized by the contents of the string. public char [] toCharArray(); 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]); }
  • 16. 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.
  • 17. 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)); } }
  • 18. 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)
  • 19. 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)
  • 20. 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]); } } }
  • 21. 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)
  • 22. • 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.
  • 23. 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)); } }
  • 24. 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.
  • 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)
  • 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.
  • 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( )