SlideShare a Scribd company logo
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

PPTX
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
PPTX
Java Strings
RaBiya Chaudhry
 
PDF
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Edureka!
 
PPT
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
PDF
Arrays string handling java packages
Sardar Alam
 
PPTX
String in java
Ideal Eyes Business College
 
PPT
String handling session 5
Raja Sekhar
 
PPT
String classes and its methods.20
myrajendra
 
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Java Strings
RaBiya Chaudhry
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Edureka!
 
Arrays string handling java packages
Sardar Alam
 
String in java
Ideal Eyes Business College
 
String handling session 5
Raja Sekhar
 
String classes and its methods.20
myrajendra
 

What's hot (20)

PPS
String and string buffer
kamal kotecha
 
PPTX
Java String
SATYAM SHRIVASTAV
 
PPTX
Strings in Java
Abhilash Nair
 
PDF
Java String
Java2Blog
 
PPTX
Java string handling
Salman Khan
 
PPTX
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
PPTX
L13 string handling(string class)
teach4uin
 
PPTX
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
PDF
String handling(string class)
Ravi Kant Sahu
 
PPTX
What is String in Java?
RAKESH P
 
PPTX
Java strings
Mohammed Sikander
 
PDF
String handling(string buffer class)
Ravi Kant Sahu
 
PPTX
String java
774474
 
PPTX
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
PPTX
Java string , string buffer and wrapper class
SimoniShah6
 
DOCX
Fundamental classes in java
Garuda Trainings
 
PPS
Wrapper class
kamal kotecha
 
DOCX
Autoboxing and unboxing
Geetha Manohar
 
PPSX
Strings in Java
Hitesh-Java
 
PDF
Wrapper classes
simarsimmygrewal
 
String and string buffer
kamal kotecha
 
Java String
SATYAM SHRIVASTAV
 
Strings in Java
Abhilash Nair
 
Java String
Java2Blog
 
Java string handling
Salman Khan
 
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
L13 string handling(string class)
teach4uin
 
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
String handling(string class)
Ravi Kant Sahu
 
What is String in Java?
RAKESH P
 
Java strings
Mohammed Sikander
 
String handling(string buffer class)
Ravi Kant Sahu
 
String java
774474
 
Autoboxing And Unboxing In Java
chathuranga kasun bamunusingha
 
Java string , string buffer and wrapper class
SimoniShah6
 
Fundamental classes in java
Garuda Trainings
 
Wrapper class
kamal kotecha
 
Autoboxing and unboxing
Geetha Manohar
 
Strings in Java
Hitesh-Java
 
Wrapper classes
simarsimmygrewal
 
Ad

Similar to Java - Strings Concepts (20)

PPTX
Java Strings.pptxJava Strings.pptxJava Strings.pptx
Shivam287777
 
PPTX
Day_5.1.pptx
ishasharma835109
 
PPT
8. String
Nilesh Dalvi
 
PDF
Lecture 7
Debasish Pratihari
 
PPT
String Handling
Bharat17485
 
PPTX
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
mohithn2004
 
PPTX
String in java, string constructors and operations
manjeshbngowda
 
PPTX
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
PPT
07slide
Aboudi Sabbah
 
PPT
Javaℱ (OOP) - Chapter 9: "Strings and Text I/O"
Gouda Mando
 
PPTX
OCA Java SE 8 Exam Chapter 3 Core Java APIs
İbrahim KĂŒrce
 
PPTX
Java String Handling
Infoviaan Technologies
 
PPTX
String handling
ssuser20c32b
 
PPT
JAVA CONCEPTS
Shivam Singh
 
PPTX
Unit-2.Arrays and Strings.pptx.................
suchitrapoojari984
 
PPS
Advance Java
Vidyacenter
 
PPTX
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
minifriendofyou
 
PPTX
package
sweetysweety8
 
PPTX
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
PPTX
DOC-20240812-WA0000 array string and.pptx
PanjatcharamVg
 
Java Strings.pptxJava Strings.pptxJava Strings.pptx
Shivam287777
 
Day_5.1.pptx
ishasharma835109
 
8. String
Nilesh Dalvi
 
Lecture 7
Debasish Pratihari
 
String Handling
Bharat17485
 
3.1 STRINGS (1) java jksdbkjdbsjsef.pptx
mohithn2004
 
String in java, string constructors and operations
manjeshbngowda
 
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
07slide
Aboudi Sabbah
 
Javaℱ (OOP) - Chapter 9: "Strings and Text I/O"
Gouda Mando
 
OCA Java SE 8 Exam Chapter 3 Core Java APIs
İbrahim KĂŒrce
 
Java String Handling
Infoviaan Technologies
 
String handling
ssuser20c32b
 
JAVA CONCEPTS
Shivam Singh
 
Unit-2.Arrays and Strings.pptx.................
suchitrapoojari984
 
Advance Java
Vidyacenter
 
String.pptxihugyftgrfxdf bnjklihugyfthfgxvhbjihugyfthcgxcgvjhbkipoihougyfctgf...
minifriendofyou
 
package
sweetysweety8
 
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
DOC-20240812-WA0000 array string and.pptx
PanjatcharamVg
 
Ad

More from Victer Paul (13)

PDF
OOAD - UML - Sequence and Communication Diagrams - Lab
Victer Paul
 
PDF
OOAD - UML - Class and Object Diagrams - Lab
Victer Paul
 
PDF
OOAD - Systems and Object Orientation Concepts
Victer Paul
 
PDF
Java - Packages Concepts
Victer Paul
 
PDF
Java - OOPS and Java Basics
Victer Paul
 
PDF
Java - Exception Handling Concepts
Victer Paul
 
PDF
Java - Class Structure
Victer Paul
 
PDF
Java - Object Oriented Programming Concepts
Victer Paul
 
PDF
Java - Basic Concepts
Victer Paul
 
PDF
Java - File Input Output Concepts
Victer Paul
 
PDF
Java - Inheritance Concepts
Victer Paul
 
PDF
Java - Arrays Concepts
Victer Paul
 
PDF
Java applet programming concepts
Victer Paul
 
OOAD - UML - Sequence and Communication Diagrams - Lab
Victer Paul
 
OOAD - UML - Class and Object Diagrams - Lab
Victer Paul
 
OOAD - Systems and Object Orientation Concepts
Victer Paul
 
Java - Packages Concepts
Victer Paul
 
Java - OOPS and Java Basics
Victer Paul
 
Java - Exception Handling Concepts
Victer Paul
 
Java - Class Structure
Victer Paul
 
Java - Object Oriented Programming Concepts
Victer Paul
 
Java - Basic Concepts
Victer Paul
 
Java - File Input Output Concepts
Victer Paul
 
Java - Inheritance Concepts
Victer Paul
 
Java - Arrays Concepts
Victer Paul
 
Java applet programming concepts
Victer Paul
 

Recently uploaded (20)

PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PPTX
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
DOCX
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 
This slide provides an overview Technology
mineshkharadi333
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Software Development Methodologies in 2025
KodekX
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 

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