SlideShare a Scribd company logo
1 of 40
Download to read offline
Java - Strings
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Introduction
 String is a sequence of characters.
 But, unlike many other languages that implement strings
as character arrays, Java implements strings as objects
of type String
 A String variable contains a collection of characters
surrounded by double quotes
 String class is used to create string object.
 The String class belongs to the java.lang package, which
does not require an import statement.
 Like other classes, String has constructors and methods.
String greeting = "Hello";
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html2Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
String object creation
 There are two ways to create String object:
 By string literal
 By new keyword
3Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Using new keyword
 The String class supports several constructors.
 To create an empty String, you call the default
constructor.
 For example,
 will create an instance of String with no characters in it
 To create a String initialized by an array of characters,
use the constructor shown here.
String s = new String();
String s1 = new String(char charvar[ ])
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
4Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Using string literal
 For each string literal in your program, Java automatically
constructs a String object.
 Thus, you can use a string literal to initialize a String
object.
 For example,
 Literal Strings ,
 are anonymous objects of the String class
 are defined by enclosing text in double quotes. “This is
a literal String”
 don’t have to be constructed.
 can be assigned to String variables.
 can be passed to methods and constructors as
parameters.
String s2 = "abc";
5Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Strings Are Immutable
 A String object is immutable; its contents cannot be
changed.
 Does the following code change the contents of the string?
 Note: String objects are stored in a special memory area
known as ”string constant pool” inside the Heap memory.
 Why java uses concept of string literal?
 To make Java more memory efficient (because no new
objects are created if it exists already in string constant
pool).
String s = "Java";
s = "HTML";
6Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Strings literal creation
 Each time you create a string literal, the JVM checks the
string constant pool first.
 If the string already exists in the pool, a reference to the
pooled instance returns.
 If the string does not exist in the pool, a new String object
instantiates, then is placed in the pool.
 For example:
 String s1="Welcome";
 String s2="Welcome";
//it will not create new object whether
will return the reference to the same
instance. It is called as Interned String
7Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
8
Trace Code
String s = "Java";
s = "HTML";
: String
String object for "Java"
s
After executing String s = "Java"; After executing s = "HTML";
: String
String object for "Java"
: String
String object for "HTML"
Contents cannot be changed
This string object is
now unreferenced
s
animation
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
9
Trace Code
String s = "Java";
s = "HTML";
: String
String object for "Java"
s
After executing String s = "Java"; After executing s = "HTML";
: String
String object for "Java"
: String
String object for "HTML"
Contents cannot be changed
This string object is
now unreferenced
s
animation
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
new String object creation
 In such case,
 JVM will create a new String object in normal(non-pool) Heap
memory and the literal "Welcome" will be placed in the string
constant pool.
 The variable s will refer to the object in Heap(non-pool).
String s = new String();
10Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
11
Examples
display
s1 == s is false
s1 == s3 is true
A new object is created if you use the
new operator.
If you use the string initializer, no new
object is created if the interned object is
already created.
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s1 == s3 is " + (s1 == s3));
: String
Interned string object for
"Welcome to Java"
: String
A string object for
"Welcome to Java"
s1
s2
s3
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
12
Trace Code
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
: String
Interned string object for
"Welcome to Java"
s1
animation
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
13
Trace Code
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
: String
Interned string object for
"Welcome to Java"
: String
A string object for
"Welcome to Java"
s1
s2
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
14
Trace Code
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
: String
Interned string object for
"Welcome to Java"
: String
A string object for
"Welcome to Java"
s1
s2
s3
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Empty Strings
 An empty String has no characters. It’s length is 0.
 Not the same as an uninitialized String.
String word1 = "";
String word2 = new String();
private String errorMsg; errorMsg
is null
Empty strings
15Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Strings Operations
16Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Strings Operations
17Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
String Length
 The length of a string is the number of characters that it
contains.
 To obtain this value, call the length( ) method, shown here:
int length( )
String message = "Welcome";
int len = message.length() // returns 7
18Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Retrieving Individual Characters
 Character positions in strings are numbered starting from 0 –
just like arrays.
 The method, Returns the char at position i.
char charAt(i);
W e l c o m e t o J a v a
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message
Indices
message.charAt(0) message.charAt(14)message.length() is 15
7
’n'
”Problem".length();
”Window".charAt (2);
Returns:
19Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
String Concatenation
 In general, Java does not allow operators to be applied to
String objects.
 There are two ways to concat string objects:
 By + (string concatenation) operator
 By concat() method
 The one exception to this rule is the + operator, which
concatenates two strings, producing a String object as the
result.
String s3 = s1.concat(s2);
String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5 same as
(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
20Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Methods — Concatenation
String word1 = “re”, word2 = “think”; word3 = “ing”;
int num = 2;
 String result = word1 + word2;
//concatenates word1 and word2 “rethink“
 String result = word1.concat (word2);
//the same as word1 + word2 “rethink“
 result += word3;
//concatenates word3 to result “rethinking”
 result += num; //converts num to String
//and concatenates it to result “rethinking2”
21Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
String Comparisons
 We can compare two given strings on the basis of content
and reference.
 It is used in authentication (by equals() method),sorting (by
compareTo() method), reference matching (by == operator)
etc.
 There are three ways to compare String objects:
 By equals() method
 By = = operator
 By compareTo() method
22Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
By equals() method
 equals() method compares the original content of the string.
It compares values of string for equality.
 String class provides two methods:
23Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
class StringEquals{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
String s5="SACHIN";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
System.out.println(s1.equals(s5));//false
System.out.println(s1.equalsIgnoreCase(s5));//true
}
} 24Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
By == operator
 The == operator compares two object references (not
values) to see whether they refer to the same instance.
class SimpleRefSame{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);
//true (because both refer to same instance)
System.out.println(s1==s3);
//false(because s3 refers to instance created in
nonpool)
}
} 25Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
By compareTo() method:
 compareTo() method compares values and returns an int
which tells if the values compare less than, equal, or greater
than.
 Suppose s1 and s2 are two string variables.
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
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 ) 26Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Comparison Examples
//negative differences
diff = “apple”.compareTo(“berry”);//a before b
diff = “Zebra”.compareTo(“apple”);//Z before a
diff = “dig”.compareTo(“dug”);//i before u
diff = “dig”.compareTo(“digs”);//dig is shorter
//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal
//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
Think about sorting names in attendance in alphabetical order 27Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
By substring() method
 A part of string is called substring. In other words, substring
is a subset of another string.
 startIndex is inclusive and endIndex is exclusive.
 You can get substring from the given String object by one of
the two methods:
28Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
By substring() method
String s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
S a c h i n e n u k a r
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
string
Indices
T
T
d
“lev"
“mutable"
"" (empty string)
”television".substring (2,5);
“immutable".substring (2);
“bob".substring (9);
Returns:
29Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Workout
contains () // check content
endsWith () // String Comparison
format () // Formatted Display
indexOf () // Searching Strings
isEmpty() // check length 0
lastIndexOf () // Searching Strings
replace () // Modifying a String
split () // Tokenizer
startsWith () // String Comparison
toLowerCase() // Changing the Case
toUpperCase() //Changing the Case
trim() // Remove Space
valueOf () //Data Conversion
30Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
StringBuffer
 StringBuffer is a peer class of String that provides much
of the functionality of strings.
 As you know, String represents fixed-length, immutable
character sequences.
 In contrast, StringBuffer represents growable and
writeable character sequences.
 StringBuffer may have characters and substrings inserted
in the middle or appended to the end.
 StringBuffer will automatically grow to make room for
such additions and often has more characters
preallocated than are actually needed, to allow room for
growth.
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html 31Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
StringBuffer Constructors
 StringBuffer defines main three constructors:
 StringBuffer( )
 StringBuffer(int size)
 StringBuffer(String str)
 The default constructor (the one with no parameters)
reserves room for 16 characters without reallocation.
 The second version accepts an integer argument that
explicitly sets the size of the buffer.
 The third version accepts a String argument that sets the
initial contents of the StringBuffer object and reserves room
for 16 more characters without reallocation.
 StringBuffer allocates room for 16 additional characters
when no specific buffer length is requested, because
reallocation is a costly process in terms of time. 32Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Modifying string in the buffer
 Append at the end of a string
 Insert new contents at a specified position in a string buffer
 Replace characters in a string buffer
 Delete the part/content of the string
33Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Methods
34Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Methods workout
35Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Methods workout
36Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Methods workout
37Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Methods workout
38Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
Review:
1. String city = "Bloomington“;
What is returned by city.charAt (2)?
2. By city.substring(2, 4)?
3. By city.lastIndexOf(‘o’)?
4. By city.indexOf(3)?
5. What does the trim method do?
6. “sam”.equals(“Sam”) returns ?
7. What kind of value does “sam”.compareTo(“Sam”) return?
8. What will be stored in s?
s = “mint”.replace(‘t’, ‘e’);
9. What does s.toUpperCase() do to s?
10. Name a simple way to convert a number into a string.
39Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
40
The End…
Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam

More Related Content

What's hot

String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
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
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?RAKESH P
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
String java
String javaString java
String java774474
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper classSimoniShah6
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in javaGaruda Trainings
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxingGeetha Manohar
 
Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 

What's hot (20)

String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Java String
Java String Java String
Java String
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java String
Java StringJava String
Java String
 
Java string handling
Java string handlingJava string handling
Java string handling
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
 
Java strings
Java   stringsJava   strings
Java strings
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String java
String javaString java
String java
 
Autoboxing And Unboxing In Java
Autoboxing And Unboxing In JavaAutoboxing And Unboxing In Java
Autoboxing And Unboxing In Java
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 

Similar to Java - Strings Concepts

Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Gouda Mando
 
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
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
Java Presentation on the topic of string
Java Presentation  on the topic of stringJava Presentation  on the topic of string
Java Presentation on the topic of stringRajTangadi
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .pptzainiiqbal761
 
Text processing
Text processingText processing
Text processingIcancode
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi_Kant_Sahu
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object ReferencesTareq Hasan
 

Similar to Java - Strings Concepts (20)

Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
8. String
8. String8. String
8. String
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
String Handling
String HandlingString Handling
String Handling
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
07slide
07slide07slide
07slide
 
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"Java™ (OOP) - Chapter 9: "Strings and Text I/O"
Java™ (OOP) - Chapter 9: "Strings and Text I/O"
 
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
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
String handling
String handlingString handling
String handling
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
package
packagepackage
package
 
Java Presentation on the topic of string
Java Presentation  on the topic of stringJava Presentation  on the topic of string
Java Presentation on the topic of string
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .ppt
 
Text processing
Text processingText processing
Text processing
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
11-ch04-3-strings.pdf
11-ch04-3-strings.pdf11-ch04-3-strings.pdf
11-ch04-3-strings.pdf
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 

More from Victer Paul

OOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - LabOOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - LabVicter Paul
 
OOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - LabOOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - LabVicter Paul
 
OOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation ConceptsOOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation ConceptsVicter Paul
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages ConceptsVicter Paul
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java BasicsVicter Paul
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling ConceptsVicter Paul
 
Java - Class Structure
Java - Class StructureJava - Class Structure
Java - Class StructureVicter Paul
 
Java - Object Oriented Programming Concepts
Java - Object Oriented Programming ConceptsJava - Object Oriented Programming Concepts
Java - Object Oriented Programming ConceptsVicter Paul
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic ConceptsVicter Paul
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output ConceptsVicter Paul
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance ConceptsVicter Paul
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays ConceptsVicter Paul
 
Java applet programming concepts
Java  applet programming conceptsJava  applet programming concepts
Java applet programming conceptsVicter Paul
 

More from Victer Paul (13)

OOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - LabOOAD - UML - Sequence and Communication Diagrams - Lab
OOAD - UML - Sequence and Communication Diagrams - Lab
 
OOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - LabOOAD - UML - Class and Object Diagrams - Lab
OOAD - UML - Class and Object Diagrams - Lab
 
OOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation ConceptsOOAD - Systems and Object Orientation Concepts
OOAD - Systems and Object Orientation Concepts
 
Java - Packages Concepts
Java - Packages ConceptsJava - Packages Concepts
Java - Packages Concepts
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java - Class Structure
Java - Class StructureJava - Class Structure
Java - Class Structure
 
Java - Object Oriented Programming Concepts
Java - Object Oriented Programming ConceptsJava - Object Oriented Programming Concepts
Java - Object Oriented Programming Concepts
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic Concepts
 
Java - File Input Output Concepts
Java - File Input Output ConceptsJava - File Input Output Concepts
Java - File Input Output Concepts
 
Java - Inheritance Concepts
Java - Inheritance ConceptsJava - Inheritance Concepts
Java - Inheritance Concepts
 
Java - Arrays Concepts
Java - Arrays ConceptsJava - Arrays Concepts
Java - Arrays Concepts
 
Java applet programming concepts
Java  applet programming conceptsJava  applet programming concepts
Java applet programming concepts
 

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

Java - Strings Concepts

  • 1. Java - Strings Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 2. Introduction  String is a sequence of characters.  But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String  A String variable contains a collection of characters surrounded by double quotes  String class is used to create string object.  The String class belongs to the java.lang package, which does not require an import statement.  Like other classes, String has constructors and methods. String greeting = "Hello"; https://docs.oracle.com/javase/7/docs/api/java/lang/String.html2Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 3. String object creation  There are two ways to create String object:  By string literal  By new keyword 3Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 4. Using new keyword  The String class supports several constructors.  To create an empty String, you call the default constructor.  For example,  will create an instance of String with no characters in it  To create a String initialized by an array of characters, use the constructor shown here. String s = new String(); String s1 = new String(char charvar[ ]) char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); 4Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 5. Using string literal  For each string literal in your program, Java automatically constructs a String object.  Thus, you can use a string literal to initialize a String object.  For example,  Literal Strings ,  are anonymous objects of the String class  are defined by enclosing text in double quotes. “This is a literal String”  don’t have to be constructed.  can be assigned to String variables.  can be passed to methods and constructors as parameters. String s2 = "abc"; 5Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 6. Strings Are Immutable  A String object is immutable; its contents cannot be changed.  Does the following code change the contents of the string?  Note: String objects are stored in a special memory area known as ”string constant pool” inside the Heap memory.  Why java uses concept of string literal?  To make Java more memory efficient (because no new objects are created if it exists already in string constant pool). String s = "Java"; s = "HTML"; 6Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 7. Strings literal creation  Each time you create a string literal, the JVM checks the string constant pool first.  If the string already exists in the pool, a reference to the pooled instance returns.  If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.  For example:  String s1="Welcome";  String s2="Welcome"; //it will not create new object whether will return the reference to the same instance. It is called as Interned String 7Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 8. 8 Trace Code String s = "Java"; s = "HTML"; : String String object for "Java" s After executing String s = "Java"; After executing s = "HTML"; : String String object for "Java" : String String object for "HTML" Contents cannot be changed This string object is now unreferenced s animation Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 9. 9 Trace Code String s = "Java"; s = "HTML"; : String String object for "Java" s After executing String s = "Java"; After executing s = "HTML"; : String String object for "Java" : String String object for "HTML" Contents cannot be changed This string object is now unreferenced s animation Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 10. new String object creation  In such case,  JVM will create a new String object in normal(non-pool) Heap memory and the literal "Welcome" will be placed in the string constant pool.  The variable s will refer to the object in Heap(non-pool). String s = new String(); 10Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 11. 11 Examples display s1 == s is false s1 == s3 is true A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created. String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; System.out.println("s1 == s2 is " + (s1 == s2)); System.out.println("s1 == s3 is " + (s1 == s3)); : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" s1 s2 s3 Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 12. 12 Trace Code String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; : String Interned string object for "Welcome to Java" s1 animation Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 13. 13 Trace Code String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" s1 s2 Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 14. 14 Trace Code String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" s1 s2 s3 Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 15. Empty Strings  An empty String has no characters. It’s length is 0.  Not the same as an uninitialized String. String word1 = ""; String word2 = new String(); private String errorMsg; errorMsg is null Empty strings 15Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 16. Strings Operations 16Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 17. Strings Operations 17Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 18. String Length  The length of a string is the number of characters that it contains.  To obtain this value, call the length( ) method, shown here: int length( ) String message = "Welcome"; int len = message.length() // returns 7 18Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 19. Retrieving Individual Characters  Character positions in strings are numbered starting from 0 – just like arrays.  The method, Returns the char at position i. char charAt(i); W e l c o m e t o J a v a 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 message Indices message.charAt(0) message.charAt(14)message.length() is 15 7 ’n' ”Problem".length(); ”Window".charAt (2); Returns: 19Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 20. String Concatenation  In general, Java does not allow operators to be applied to String objects.  There are two ways to concat string objects:  By + (string concatenation) operator  By concat() method  The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 same as (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5); 20Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 21. Methods — Concatenation String word1 = “re”, word2 = “think”; word3 = “ing”; int num = 2;  String result = word1 + word2; //concatenates word1 and word2 “rethink“  String result = word1.concat (word2); //the same as word1 + word2 “rethink“  result += word3; //concatenates word3 to result “rethinking”  result += num; //converts num to String //and concatenates it to result “rethinking2” 21Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 22. String Comparisons  We can compare two given strings on the basis of content and reference.  It is used in authentication (by equals() method),sorting (by compareTo() method), reference matching (by == operator) etc.  There are three ways to compare String objects:  By equals() method  By = = operator  By compareTo() method 22Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 23. By equals() method  equals() method compares the original content of the string. It compares values of string for equality.  String class provides two methods: 23Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 24. class StringEquals{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); String s4="Saurav"; String s5="SACHIN"; System.out.println(s1.equals(s2));//true System.out.println(s1.equals(s3));//true System.out.println(s1.equals(s4));//false System.out.println(s1.equals(s5));//false System.out.println(s1.equalsIgnoreCase(s5));//true } } 24Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 25. By == operator  The == operator compares two object references (not values) to see whether they refer to the same instance. class SimpleRefSame{ public static void main(String args[]){ String s1="Sachin"; String s2="Sachin"; String s3=new String("Sachin"); System.out.println(s1==s2); //true (because both refer to same instance) System.out.println(s1==s3); //false(because s3 refers to instance created in nonpool) } } 25Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 26. By compareTo() method:  compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.  Suppose s1 and s2 are two string variables. s1 == s2 :0 s1 > s2 :positive value s1 < s2 :negative value 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 ) 26Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 27. Comparison Examples //negative differences diff = “apple”.compareTo(“berry”);//a before b diff = “Zebra”.compareTo(“apple”);//Z before a diff = “dig”.compareTo(“dug”);//i before u diff = “dig”.compareTo(“digs”);//dig is shorter //zero differences diff = “apple”.compareTo(“apple”);//equal diff = “dig”.compareToIgnoreCase(“DIG”);//equal //positive differences diff = “berry”.compareTo(“apple”);//b after a diff = “apple”.compareTo(“Apple”);//a after A diff = “BIT”.compareTo(“BIG”);//T after G diff = “huge”.compareTo(“hug”);//huge is longer Think about sorting names in attendance in alphabetical order 27Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 28. By substring() method  A part of string is called substring. In other words, substring is a subset of another string.  startIndex is inclusive and endIndex is exclusive.  You can get substring from the given String object by one of the two methods: 28Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 29. By substring() method String s="Sachin Tendulkar"; System.out.println(s.substring(6));//Tendulkar System.out.println(s.substring(0,6));//Sachin S a c h i n e n u k a r 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 string Indices T T d “lev" “mutable" "" (empty string) ”television".substring (2,5); “immutable".substring (2); “bob".substring (9); Returns: 29Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 30. Workout contains () // check content endsWith () // String Comparison format () // Formatted Display indexOf () // Searching Strings isEmpty() // check length 0 lastIndexOf () // Searching Strings replace () // Modifying a String split () // Tokenizer startsWith () // String Comparison toLowerCase() // Changing the Case toUpperCase() //Changing the Case trim() // Remove Space valueOf () //Data Conversion 30Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 31. StringBuffer  StringBuffer is a peer class of String that provides much of the functionality of strings.  As you know, String represents fixed-length, immutable character sequences.  In contrast, StringBuffer represents growable and writeable character sequences.  StringBuffer may have characters and substrings inserted in the middle or appended to the end.  StringBuffer will automatically grow to make room for such additions and often has more characters preallocated than are actually needed, to allow room for growth. https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html 31Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 32. StringBuffer Constructors  StringBuffer defines main three constructors:  StringBuffer( )  StringBuffer(int size)  StringBuffer(String str)  The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.  The second version accepts an integer argument that explicitly sets the size of the buffer.  The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.  StringBuffer allocates room for 16 additional characters when no specific buffer length is requested, because reallocation is a costly process in terms of time. 32Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 33. Modifying string in the buffer  Append at the end of a string  Insert new contents at a specified position in a string buffer  Replace characters in a string buffer  Delete the part/content of the string 33Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 34. Methods 34Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 35. Methods workout 35Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 36. Methods workout 36Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 37. Methods workout 37Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 38. Methods workout 38Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 39. Review: 1. String city = "Bloomington“; What is returned by city.charAt (2)? 2. By city.substring(2, 4)? 3. By city.lastIndexOf(‘o’)? 4. By city.indexOf(3)? 5. What does the trim method do? 6. “sam”.equals(“Sam”) returns ? 7. What kind of value does “sam”.compareTo(“Sam”) return? 8. What will be stored in s? s = “mint”.replace(‘t’, ‘e’); 9. What does s.toUpperCase() do to s? 10. Name a simple way to convert a number into a string. 39Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam
  • 40. 40 The End… Dr. P. Victer Paul, Indian Institute of Information Technology Kottayam