Core Java 2022
Learning Objectives:
➢ String Handling
➢ Different ways to create string
➢ Immutability vs Mutability
➢ Working the important methods of String.
➢ String Interning
➢ Creating User-defined Immutable class
Page 1
Core Java 2022
String Handling
➢ String is nothing but a group of characters or character array.
Eg:
Sai, Hyderabad, India, abc@[Link], [Link]
➢ If we want to represent a group of character then we should go for String object
➢ String is a final class present in [Link] package.
➢ String is an immutable class.
➢ .equals() of Object class is overridden for content comparison in String class.
➢ toString() of Object class is overridden to present proper string.
Different ways to create String object:
There are 2 ways to create String object:
1. By using literal
2. By using new operator
Creating a string object by using literal:
class Test {
public static void main(String[] args) {
String s1 = "adi";
String s2 = "seshu";
String s3 = "adi";
[Link](s1);
[Link](s2);
[Link](s3);
}
}
Whenever we create string object by using String literal syntax, first JVM goes to SCP (String Constant Pool)
and check if the string is already present in the pool or not.
If it is available, it returns the existing reference from the pool, otherwise a new String object is created.
Page 2
Core Java 2022
In the above example two objects are available
➢ First time JVM will not find any string object with the name “adi” so JVM creates a new object.
➢ Second time JVM will not find any String object with the name “seshu” so JVM creates the new object
one more time.
➢ Third time JVM will find the string object with the content “adi” at this time JVM wont creates any new
object just JVM returns the reference to the same instance.
Advantage of creating string object using literal is efficient memory management;
As duplicate objects are not presented in the String Constant Pool Area then, the objects which is present in
the SCP area are unique objects.
Page 3
Core Java 2022
Creating a string object by using new operator: -
class Test {
public static void main(String[] args) {
String s1 = new String("adi");
String s2 = new String("seshu");
String s3 = new String("adi");
[Link](s1);
[Link](s2);
[Link](s3);
}
}
Whenever string object is created by using new operator, JVM creates two objects, one is in heap and another
one is in SCP.
class Test {
public static void main(String[] args) {
String s1 = new String("adi");
String s2 = new String("seshu");
String s3 = new String("adi");
[Link]([Link](s2));
[Link]([Link](s3));
[Link]([Link](s3));
[Link](s1==s2);
[Link](s1==s3);
[Link](s2==s3);
}
}
Page 4
Core Java 2022
Diff b/w creating String by using new operator and literal?
String s=new String(“adi”); String s=”adi”;
In this case 2 objects will be created. In this case only one object will be created in SCP.
One is in heap and other is in SCP. s is always pointing to that object present in SCP
S is always pointing to heap.
Q: Which approach is best to create String object either using literal or new operator?
class Test {
public static void main(String args[]){
long start1 = [Link]();
for (int i = 0; i < 1000000; i++){
String s1 = "hi";
}
long end1 = [Link]();
long total_time1 = end1 - start1;
[Link]("Time taken to execute string literal:"+total_time1);
long start2 = [Link]();
for (int i = 0; i < 1000000; i++){
String s3 = new String("hi");
}
long end2 = [Link]();
long total_time2 = end2 - start2;
[Link]("Time taken to execute string object:"+total_time2);
}
}
Ans:
Creating String object using String Literal is best.
Page 5
Core Java 2022
Interning of String:
By using intern() method with the help of Heap object reference, we are able to access the corresponding SCP
object. This process is called Interning of String.
class Test {
public static void main(String[] args) {
String s1 = new String("sai");
String s2 = [Link]();
String s3 = "sai";
[Link](s1==s2);
[Link](s2==s3);
}
}
false
true
Page 6
Core Java 2022
Immutability VS mutability
Immutability:
class Test {
public static void main(String[] args) {
String s = new String("abc");
[Link](s);
[Link]("xyz");
[Link](s);
}
}
Once an object is created, no modifications are allowed on the existing object.
If we try to perform any changes on the existing object, with those changes a new object will be created.
This non changeable behavior is nothing but immutability.
abc
abc
Following are the immutable classes in Java:
String, File, All Wrapper Classes like Integer, Double, Character, etc
Page 7
Core Java 2022
Mutability:
class Test {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("adi");
[Link](sb);
[Link]("seshu");
[Link](sb);
}
}
output:
adi
adiseshu
Once an object is created, all changes are allowed in the existing object.
This changeable behavior is nothing but Mutability.
Example:
StringBuffer
Immutability Mutability
String s=new String(“adi”); StringBuffer sb=new StringBuffer(“adi”);
[Link](“seshu”); [Link](“seshu”);
sopln(s);----------------------→adi sopln(sb);---------------→adiseshu
Page 8
Core Java 2022
Why should we go for immutability?
A single object may be used by multiple references.
If we are allowed to perform any changes in existing object by using one reference, then the remaining
references will be affected.
To prevent this Java People introduced immutability concept.
How are we getting immutability in the case of String?
➢ Java People introduced SCP concept to achieve immutability.
What is String Constant Pool?
➢ In our program any String object required to be used repeatedly, then it is never recommended to create
a new object every time, because it creates memory problem and effects performance of the system.
➢ To overcome these, Java People introduced a special concept String Constant Pool.
➢ In SCP, a single object is created and it can be reused for every requirement.
Why Java people define SCP like concept only for the String?
➢ String is the most commonly used object in any java program.
➢ Hence to improve the performance and memory utilization Java people defined SCP concept for String.
What are Immutable classes in java?
Following are the only immutable classes in java.
1. String
2. All Wrapper classes (Integer, Character, Boolean, etc)
3. File
Page 9
Core Java 2022
Creating our own immutable class:
To create a class immutable, we need to follow following steps:
1. Declare the class as final so it can’t be extended from child classes.
2. Data members in the class must be declared private so that direct access is not allowed.
3. Data members in the class must be declared as final so that we can’t change the value of it after
object creation.
4. Initialize all the fields via a constructor.
5. Override toString() to print proper representation of an object.
final class Student {
private final String name;
public Student(String name) {
[Link] = name;
}
public Student modify(String name){
if([Link] == name)
return this;
else
return new Student(name);
}
public String toString(){
return name;
}
}
public class Test {
public static void main(String[] args){
Student s1=new Student("adi");
Student s2 = [Link]("adi");
Student s3 = [Link]("seshu");
[Link](s1 == s2);
[Link](s1 == s3);
}
}
Page 10
Core Java 2022
Important methods of String class:
concat(String s):-
It is used to combine the two Strings.
We can also use ‘+’ operator for concatenation.
class Test {
public static void main(String[] args) {
String s1 = "adi";
String s2 = "seshu";
[Link]([Link](s2));
[Link](s1+s2);
}
}
length():-
It is used to find out the length of the string.
class Test {
public static void main(String[] args) {
String s1 = "adi";
String s2 = "seshu";
[Link]([Link]());
[Link]([Link]());
int[] x = new int[] {10,20,30};
[Link]([Link]);
}
}
charAt(int index):-
It is used to extract the character from particular index position.
class Test {
public static void main(String[] args) {
String s = "adi";
[Link]([Link](0));
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
}
}
Page 11
Core Java 2022
import [Link];
class Test {
public static void main(String[] args) {
char gender;
Scanner in = new Scanner([Link]);
[Link]("Enter gender:");
gender = [Link]().charAt(0);
if(gender=='M')
[Link]("male");
else if(gender=='F')
[Link]("female");
else
[Link]("Invalid");
}
}
String[] split(String):-
It is used to divide the given string into number of tokens.
class Test {
public static void main(String[] args) {
String s="Java is an object oriented programming language";
String[] tokens = [Link](" ");
for(String token : tokens){
[Link](token);
}
}
}
public boolean equals():-
➢ Object class equals() method is overridden for content comparison in String class.
➢ It returns true if 2 objects content is same otherwise returns false.
True----------if two Strings are same
False-------- if two strings are not equals
class Test {
public static void main(String[] args) {
String userId = new String("adi");
String password = new String("seshu");
if([Link]("adi") && [Link]("seshu"))
//if(userId == "adi" && password == "seshu")
[Link]("success");
else
[Link]("fails");
}
}
Page 12
Core Java 2022
equalsIgnoreCase(String):
➢ It compares the string whether the content is same or not.
➢ It ignores the case.
class Test {
public static void main(String[] args) {
String userId = "aDi";
String password = "seshu";
if([Link]("adi") && [Link]("seshu"))
[Link]("success");
else
[Link]("fails");
}
}
byte[] getBytes():
➢ By using this method we are converting String into the byte[] .
➢ The main aim of the converting String into the byte[] format is some of the networks are supporting to
transfer the data in the form of bytes only at that situation is conversion is mandatory.
class Test {
public static void main(String[] args) {
String str = "Java Programming is very easy";
byte[] b = [Link]();
for(byte b1: b){
[Link](b1);
}
String str1 = new String(b);
[Link](str1);
}
}
toCharArray():
Used to convert the given string into char[]
class Test {
public static void main(String[] args) {
String s1 = "Programming";
char[] c = [Link]();
for (char x : c) {
[Link](x);
}
String s2 = new String(c);
[Link](s2);
}
}
Page 13
Core Java 2022
trim():-
It is used to remove the white space at beginning and ending , and save memory
class Test {
public static void main(String[] args) {
String s = " Java ";
[Link]([Link]());
[Link]([Link]());
[Link]([Link]().length());
String s2 = " J a v a ";
[Link]([Link]());
[Link]([Link]());
[Link]([Link]().length());
}
}
Ex: without trim
class Test {
public static void main(String[] args) {
String userId = " adi";
String password = "seshu";
if([Link]("adi") && [Link]("seshu"))
[Link]("success");
else
[Link]("fails");
}
}
Ex: with trim
class Test {
public static void main(String[] args) {
String userId = " adi";
String password = "seshu";
if([Link]().equals("adi") && [Link]("seshu"))
[Link]("success");
else
[Link]("fails");
}
}
Page 14
Core Java 2022
replace(char oldchar, char newchar)
and
replace(String oldString, String newString):-
By using above method we are replacing the particular character of the String. And particular portion
of the string.
class Test {
public static void main(String[] args) {
String s = "Java is very easy language ";
[Link]([Link]('J', 'L'));
[Link]([Link]("is", "is not"));
}
}
toUpperCase() and toLowerCase():-
To convert the lower case to the uppercase and uppercase to lowercase character.
class Test {
public static void main(String[] args) {
String s = "proGraMminG";
[Link](s);
[Link]([Link]());
[Link]([Link]());
}
}
Page 15
Core Java 2022
endsWith() is used to find out if the string is ending with particular character/string or not.
startsWith() used to find out the particular String starting with particular character/string or not.
class Test {
public static void main(String[] args) {
String s = "abc@[Link]";
[Link]([Link]("a"));
[Link]([Link](".com"));
}
}
class Test {
public static void main(String[] args) {
String userId = "sai";
if(!([Link]("@[Link]")))
[Link]([Link]("@[Link]"));
}
}
substring(int startingposition) and substring(int startingposition,int endingposition):
By using above method we are able to get substring from the whole String.
class Test {
public static void main(String[] args) {
String s1 = "Java is a language";
[Link]([Link](4));
[Link]([Link](0, 4));
}
}
Page 16