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
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
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