SlideShare une entreprise Scribd logo
1  sur  28
StringString
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Java and Data StructuresJava and Data Structures
Introduction
• String is a sequence of characters.
• But in java, string is an object that represents a
sequence of characters.
• String class is used to create string object.
• Creating String object:
– By String literal
– By new keyword
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Using String Literal
• Java String literal can be created using double quotes.
• For Example:
String s = “Hello”;
• Each time you create a string literal, the JVM checks the string constant pool
first.
String s1=“Hello";
String s2=“Hello";//will not create new instance
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
“Hello”
String const pool
s2
s1
Using new keyword
String s = new String("Welcome");
• In such case, JVM will create a new string object in normal heap
memory and the literal "Welcome" will be placed in the string
constant pool.
• The variable s will refer to the object in heap.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
No. Method Description
1 char charAt(int index) returns char value for the particular
index
2 int length() returns string length
3 String substring(int beginIndex) returns substring for given begin index
4 String substring(int beginIndex, int endIndex)returns substring for given begin index
and end index
5 boolean contains(CharSequence s) returns true or false after matching the
sequence of char value
6 static String join(CharSequence delimiter, CharSequence... elements)returns a joined string
7 boolean equals(Object another) checks the equality of string with object
8 boolean isEmpty() checks if string is empty
9 String concat(String str) concatenates specified string
String methods
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
No. Method Description
10 String replace(char old, char new) replaces all occurrences of specified
char value
11 String replace(CharSequence old,
CharSequence new)
replaces all occurrences of specified
CharSequence
12 String trim() returns trimmed string omitting leading
and trailing spaces
13 String split(String regex) returns splitted string matching regex
14 String split(String regex, int limit) returns spitted string matching regex
and limit
15 int indexOf(int ch) returns specified char value index
16 int indexOf(int ch, int fromIndex) returns specified char value index
starting with given index
17 int indexOf(String substring) returns specified substring index
18 int indexOf(String substring, int
fromIndex)
returns specified substring index
starting with given index
Immutable String
• String objects are immutable.
• Immutable simply means unmodifiable or
unchangeable.
• Once string object is created its data or state can't be
changed but a new string object is created.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Immutable String
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class ImmutableString
{
public static void main(String args[])
{
String s = “Patkar";
s.concat(" College”);
System.out.println(s);
}
}
“Patkar”
“Patkar College”
String const pool
s
Immutable String
But, if we explicitly assign it to the reference variable, it
will refer to “Patkar College" object
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class ImmutableString
{
public static void main(String args[])
{
String s = “Patkar";
s = s.concat(" College”);
System.out.println(s);
}
}
Why string objects are immutable in java?
• Because java uses the concept of string literal.
• Suppose there are 5 reference variables, all refers to
one object “Patkar".
• If one reference variable changes the value of the
object, it will be affected to all the reference
variables.
• That is why string objects are immutable in java.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String Comparison
• We can compare two given strings on the basis of
content and reference.
• There are three ways to compare String objects:
– By equals() method
– By = = operator
– By compareTo() method
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Using equals()
• equals() method compares the original content of
the string.
• It compares values of string for equality.
• String class provides two methods:
– public boolean equals(Object another){} compares this
string to the specified object.
– public boolean equalsIgnoreCase(String another){}
compares this String to another String, ignoring case.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Using equals()
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
Using equalsIgnoreCase()
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
Using == operator
The = = operator compares references not values.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true
System.out.println(s1==s3);//false
Using compareTo()
• compareTo() method compares values and returns
an int which tells if the values compare less than,
equal, or greater than.
• Uses lexicographical order.
• Suppose s1 and s2 are two string variables.
• If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Using compareTo()
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1)
String Concatenation
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String s1=“Pat“ + “kar”;
String s2=“ College";
String s3= s1.concat(s2);
String Spilt
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
String str = "abc:pqr:xyz:mno";
String[] splits = str.split(":");
System.out.println("splits.size: " +
splits.length);
for(String n: splits)
{
System.out.println(n);
}
StringBuffer class:
• The StringBuffer class is used to created mutable
(modifiable) string.
• The StringBuffer class is same as String except it is
mutable i.e. it can be changed.
• Commonly used Constructors of StringBuffer class:
– StringBuffer(): creates an empty string buffer with the initial capacity of
16.
– StringBuffer(String str): creates a string buffer with the specified string.
– StringBuffer(int capacity): creates an empty string buffer with the
specified capacity as length.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
StringBuffer class Methods:
• append(String s)
• insert(int offset, String s)
• replace(int startIndex, int endIndex, String str)
• delete(int startIndex, int endIndex)
• reverse()
• capacity()
• charAt(int index)
• length()
• substring(int beginIndex)
• substring(int beginIndex, int endIndex)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
append()
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class A
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java");//now original string is
changed
System.out.println(sb);//prints Hello Java
}
}
capacity()
• The capacity() method of StringBuffer class returns the current
capacity of the buffer.
• The default capacity of the buffer is 16.
• If the number of character increases from its current capacity, it
increases the capacity by (oldcapacity*2)+2.
• For example, if your current capacity is 16, it will be
(16*2)+2=34.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
capacity()
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34
toString()
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
class Student
{
String name;
Student(String name)
{
this.name=name;
}
public String toString()//overriding toString() method
{
return name;
}
public static void main(String args[])
{
Student s1 = new Student("Ram");
System.out.println(s1);
//compiler writes here s1.toString()
}
}
StringTokenizer class:
• The java.util.StringTokenizer class allows you to break
a string into tokens.
• It is simple way to break string.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
StringTokenizer class:
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
import java.util.StringTokenizer;
public class Simple
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer
(“111 222 hhh lll"," ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Q & A

Contenu connexe

Tendances

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in JavaMudit Gupta
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part VHari Christian
 
Compilers Are Databases
Compilers Are DatabasesCompilers Are Databases
Compilers Are DatabasesMartin Odersky
 
Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 
Session 05 - Strings in Java
Session 05 - Strings in JavaSession 05 - Strings in Java
Session 05 - Strings in JavaPawanMM
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classesteach4uin
 
Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Yeardezyneecole
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 

Tendances (17)

String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Generics
GenericsGenerics
Generics
 
List classes
List classesList classes
List classes
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part V
 
Compilers Are Databases
Compilers Are DatabasesCompilers Are Databases
Compilers Are Databases
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Session 05 - Strings in Java
Session 05 - Strings in JavaSession 05 - Strings in Java
Session 05 - Strings in Java
 
wrapper classes
wrapper classeswrapper classes
wrapper classes
 
L9 wrapper classes
L9 wrapper classesL9 wrapper classes
L9 wrapper classes
 
Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Year
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
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
 
Java Day-5
Java Day-5Java Day-5
Java Day-5
 

Similaire à 8. String

Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdflearnEnglish51
 
Java - Strings Concepts
Java - Strings ConceptsJava - Strings Concepts
Java - Strings ConceptsVicter Paul
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanKavita Ganesan
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string classfedcoordinator
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi_Kant_Sahu
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packagesSardar Alam
 
Text processing
Text processingText processing
Text processingIcancode
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
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
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10mlrbrown
 

Similaire à 8. String (20)

Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
Strings in java
Strings in javaStrings in java
Strings in java
 
07slide
07slide07slide
07slide
 
Java - Strings Concepts
Java - Strings ConceptsJava - Strings Concepts
Java - Strings Concepts
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
Java Strings
Java StringsJava Strings
Java Strings
 
Text processing
Text processingText processing
Text processing
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Strings
StringsStrings
Strings
 
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...
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 
Cso gaddis java_chapter10
Cso gaddis java_chapter10Cso gaddis java_chapter10
Cso gaddis java_chapter10
 
String Handling
String HandlingString Handling
String Handling
 

Plus de Nilesh Dalvi

6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception HandlingNilesh Dalvi
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and IntefacesNilesh Dalvi
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of JavaNilesh Dalvi
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending ClassesNilesh Dalvi
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructorsNilesh Dalvi
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cppNilesh Dalvi
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 

Plus de Nilesh Dalvi (16)

14. Linked List
14. Linked List14. Linked List
14. Linked List
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 

Dernier

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Dernier (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

8. String

  • 1. StringString By Nilesh Dalvi Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College. http://www.slideshare.net/nileshdalvi01 Java and Data StructuresJava and Data Structures
  • 2. Introduction • String is a sequence of characters. • But in java, string is an object that represents a sequence of characters. • String class is used to create string object. • Creating String object: – By String literal – By new keyword Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 3. Using String Literal • Java String literal can be created using double quotes. • For Example: String s = “Hello”; • Each time you create a string literal, the JVM checks the string constant pool first. String s1=“Hello"; String s2=“Hello";//will not create new instance Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). “Hello” String const pool s2 s1
  • 4. Using new keyword String s = new String("Welcome"); • In such case, JVM will create a new string object in normal heap memory and the literal "Welcome" will be placed in the string constant pool. • The variable s will refer to the object in heap. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 5. String methods Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). No. Method Description 1 char charAt(int index) returns char value for the particular index 2 int length() returns string length 3 String substring(int beginIndex) returns substring for given begin index 4 String substring(int beginIndex, int endIndex)returns substring for given begin index and end index 5 boolean contains(CharSequence s) returns true or false after matching the sequence of char value 6 static String join(CharSequence delimiter, CharSequence... elements)returns a joined string 7 boolean equals(Object another) checks the equality of string with object 8 boolean isEmpty() checks if string is empty 9 String concat(String str) concatenates specified string
  • 6. String methods Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). No. Method Description 10 String replace(char old, char new) replaces all occurrences of specified char value 11 String replace(CharSequence old, CharSequence new) replaces all occurrences of specified CharSequence 12 String trim() returns trimmed string omitting leading and trailing spaces 13 String split(String regex) returns splitted string matching regex 14 String split(String regex, int limit) returns spitted string matching regex and limit 15 int indexOf(int ch) returns specified char value index 16 int indexOf(int ch, int fromIndex) returns specified char value index starting with given index 17 int indexOf(String substring) returns specified substring index 18 int indexOf(String substring, int fromIndex) returns specified substring index starting with given index
  • 7. Immutable String • String objects are immutable. • Immutable simply means unmodifiable or unchangeable. • Once string object is created its data or state can't be changed but a new string object is created. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 8. Immutable String Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class ImmutableString { public static void main(String args[]) { String s = “Patkar"; s.concat(" College”); System.out.println(s); } } “Patkar” “Patkar College” String const pool s
  • 9. Immutable String But, if we explicitly assign it to the reference variable, it will refer to “Patkar College" object Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class ImmutableString { public static void main(String args[]) { String s = “Patkar"; s = s.concat(" College”); System.out.println(s); } }
  • 10. Why string objects are immutable in java? • Because java uses the concept of string literal. • Suppose there are 5 reference variables, all refers to one object “Patkar". • If one reference variable changes the value of the object, it will be affected to all the reference variables. • That is why string objects are immutable in java. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 11. String Comparison • We can compare two given strings on the basis of content and reference. • There are three ways to compare String objects: – By equals() method – By = = operator – By compareTo() method Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 12. Using equals() • equals() method compares the original content of the string. • It compares values of string for equality. • String class provides two methods: – public boolean equals(Object another){} compares this string to the specified object. – public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 13. Using equals() Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); String s4="Saurav"; System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s3));//true System.out.println(s1.equals(s4));//false
  • 14. Using equalsIgnoreCase() Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). String s1="Sachin"; String s2="SACHIN"; System.out.println(s1.equals(s2));//false System.out.println(s1.equalsIgnoreCase(s2));//true
  • 15. Using == operator The = = operator compares references not values. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); System.out.println(s1==s2);//true System.out.println(s1==s3);//false
  • 16. Using compareTo() • compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than. • Uses lexicographical order. • Suppose s1 and s2 are two string variables. • If: s1 == s2 :0 s1 > s2 :positive value s1 < s2 :negative value Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 17. Using compareTo() Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). String s1="Sachin"; String s2="Sachin"; String s3="Ratan"; System.out.println(s1.compareTo(s2));//0 System.out.println(s1.compareTo(s3));//1(because s1>s3) System.out.println(s3.compareTo(s1));//-1(because s3 < s1)
  • 18. String Concatenation Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). String s1=“Pat“ + “kar”; String s2=“ College"; String s3= s1.concat(s2);
  • 19. String Spilt Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). String str = "abc:pqr:xyz:mno"; String[] splits = str.split(":"); System.out.println("splits.size: " + splits.length); for(String n: splits) { System.out.println(n); }
  • 20. StringBuffer class: • The StringBuffer class is used to created mutable (modifiable) string. • The StringBuffer class is same as String except it is mutable i.e. it can be changed. • Commonly used Constructors of StringBuffer class: – StringBuffer(): creates an empty string buffer with the initial capacity of 16. – StringBuffer(String str): creates a string buffer with the specified string. – StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 21. StringBuffer class Methods: • append(String s) • insert(int offset, String s) • replace(int startIndex, int endIndex, String str) • delete(int startIndex, int endIndex) • reverse() • capacity() • charAt(int index) • length() • substring(int beginIndex) • substring(int beginIndex, int endIndex) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 22. append() Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class A { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello "); sb.append("Java");//now original string is changed System.out.println(sb);//prints Hello Java } }
  • 23. capacity() • The capacity() method of StringBuffer class returns the current capacity of the buffer. • The default capacity of the buffer is 16. • If the number of character increases from its current capacity, it increases the capacity by (oldcapacity*2)+2. • For example, if your current capacity is 16, it will be (16*2)+2=34. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 24. capacity() Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). StringBuffer sb=new StringBuffer(); System.out.println(sb.capacity());//default 16 sb.append("Hello"); System.out.println(sb.capacity());//now 16 sb.append("java is my favourite language"); System.out.println(sb.capacity());//now (16*2)+2=34
  • 25. toString() Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). class Student { String name; Student(String name) { this.name=name; } public String toString()//overriding toString() method { return name; } public static void main(String args[]) { Student s1 = new Student("Ram"); System.out.println(s1); //compiler writes here s1.toString() } }
  • 26. StringTokenizer class: • The java.util.StringTokenizer class allows you to break a string into tokens. • It is simple way to break string. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 27. StringTokenizer class: Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). import java.util.StringTokenizer; public class Simple { public static void main(String args[]) { StringTokenizer st = new StringTokenizer (“111 222 hhh lll"," "); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } }
  • 28. Q & A