Advanced Java String Handling Guide
Advanced Java String Handling Guide
Advanced JAVA
23CSP512
MODULE 2
String Handling:
The String Constructors, String Length, Special String Operations, Character Extraction, String
Changing the Case of Characters Within a String, joining strings, Additional String Methods,
StringBuffer , StringBuilder
Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
CharSequence Interface
The Java String is immutable which means it cannot be changed. Whenever we change any
string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder
classes.
We will discuss immutable string later. Let's first understand what String in Java is and how to
create the String object.
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The [Link] class is used to create a string object.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
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 is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".
To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).
2) By new keyword
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 a heap (non-pool).
[Link]
Output:
java
strings
example
The above code, converts a char array into a String object. And displays the String objects s1,
s2, and s3 on console using println() method.
The [Link] class provides many useful methods to perform operations on sequence of
char values.
6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String
objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once String object is created its data or state can't be changed but a new String object is created.
Let's try to understand the concept of immutability by the example given below:
[Link]
ADVERTISEMENT
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
[Link](" Tendulkar");//concat() method appends the string at the end
[Link](s);//will print Sachin because strings are immutable objects
}
}
Test it Now
Output:
Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".
But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.
For example:
[Link]
ADVERTISEMENT
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=[Link](" Tendulkar");
[Link](s);
}
}
Test it Now
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument. Consider, if the String object is
modifiable, the value might be changed and the class that is supposed to be loaded might be
different.
2. Thread Safe:
As the String object is immutable we don't have to take care of the synchronization that is
required while sharing an object across multiple threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further errors by loading the
correct class. This leads to making the application program more secure. Consider an example of
banking software. The username and password cannot be modified by any intruder because
String objects are immutable. This can make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory. When we try to
declare a new String object, the JVM checks whether the value already exists in the String pool
or not. If it exists, the same value is assigned to the new object. This feature allows Java to use
the heap space efficiently.
The reason behind the String class being final is because no one can override the methods of the
String class. So that it can provide the same features to the new String objects as well as to the
old ones.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
The String class equals() method compares the original content of the string. It compares values
of string for equality. String class provides the following two methods:
o public boolean equals(Object another) compares this string to the specified object.
o public boolean equalsIgnoreCase(String another) compares this string to another
string, ignoring case.
[Link]
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
[Link]([Link](s2));//true
[Link]([Link](s3));//true
[Link]([Link](s4));//false
}
}
Test it Now
Output:
true
true
false
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
[Link]
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
[Link]([Link](s2));//false
[Link]([Link](s2));//true
}
}
Test it Now
Output:
false
true
In the above program, the methods of String class are used. The equals() method returns true if
String objects are matching and both strings are of same case. equalsIgnoreCase() returns true
regardless of cases of strings.
2) By Using == operator
[Link]
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
[Link](s1==s2);//true (because both refer to same instance)
[Link](s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
Test it Now
Output:
true
false
[Link]
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
[Link]([Link](s2));//0
[Link]([Link](s3));//1(because s1>s3)
[Link]([Link](s1));//-1(because s3 < s1 )
}
}
Test it Now
Output:
0
1
-1
[Link]
class TestStringConcatenation1{
public static void main(String args[]){
Output:
Sachin Tendulkar
In Java, String concatenation is implemented through the StringBuilder (or StringBuffer) class
and it's append method. String concatenation operator produces a new String by appending the
second operand onto the end of the first operand. The String concatenation operator can
concatenate not only String but primitive values also. For Example:
[Link]
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
[Link](s);//80Sachin4040
}
}
Test it Now
Output:
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
[Link]
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=[Link](s2);
[Link](s3);//Sachin Tendulkar
}
} Test it Now
Output:
Sachin Tendulkar
The above Java program, concatenates two String objects s1 and s2 using concat() method and
stores the result into s3 object.
[Link]
Output:
Hello World
In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores the
result of concatenation of s1 and s2 using append() method.
[Link]
Output:
Hello World
The [Link]() method is available in Java version 8 and all the above versions. [Link]()
method accepts arguments first a separator and an array of String objects.
[Link]:
Output:
Hello World
In the above code snippet, the String object s stores the result of [Link]("",s1,s2) method. A
separator is specified inside quotation marks followed by the String objects or array of String
objects.
[Link]
[Link]("Hello"); //String 1
[Link]("World"); //String 2
[Link]([Link]()); //Displays result
}
}
Output:
Hello, World
In the above code snippet, the StringJoiner object s is declared and the constructor StringJoiner()
accepts a separator value. A separator is specified inside quotation marks. The add() method
appends Strings passed as arguments.
The Collectors class in Java 8 offers joining() method that concatenates the input elements in a
similar order as they occur.
[Link]
import [Link].*;
import [Link];
public class ColJoining
{
/* Driver Code */
public static void main(String args[])
{
List<String> liststr = [Link]("abc", "pqr", "xyz"); //List of String array
String str = [Link]().collect([Link](", ")); //performs joining operatio
[Link]([Link]()); //Displays result
}
}
Output:
Here, a list of String array is declared. And a String object str stores the result
of [Link]() method.
Substring in Java
A part of String is called substring. In other words, substring is a subset of another String. Java
String class provides the built-in substring() method that extract a substring from the given string
by using the index values passed as an argument. In case of substring() method startIndex is
inclusive and endIndex is exclusive.
Suppose the string is "computer", then the substring will be com, compu, ter, etc.
You can get substring from the given String object by one of the two methods:
In case of String:
o startIndex: inclusive
o endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
String s="hello";
[Link]([Link](0,2)); //returns he as a substring
In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end
index is exclusive).
[Link]
Output:
The above Java programs, demonstrates variants of the substring() method of String class. The
startindex is inclusive and endindex is exclusive.
[Link]
import [Link].*;
Output:
In the above program, we have used the split() method. It accepts an argument \\. that checks a in
the sentence and splits the string into another string. It is stored in an array of String objects
sentences.
Java String is a powerful concept because everything is treated as a String if you submit any
form in window based, web based or mobile application.
[Link]
Output:
SACHIN
sachin
Sachin
[Link]
Output:
Sachin
Sachin
[Link]
Output:
true
true
[Link]
Output:
S
h
[Link]
}
} Test it Now
Output:
When the intern method is invoked, if the pool already contains a String equal to this String
object as determined by the equals(Object) method, then the String from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is returned.
[Link]
Output:
Sachin
[Link]
{
int a=10;
String s=[Link](a);
[Link](s+10);
}
}
Output:
1010
[Link]
Output:
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So
it is safe and will result in an order.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(int capacity) It creates an empty String buffer with the specified capacity as length.
public synchronized append(String s) It is used to append the specified string with this string. The
StringBuffer append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
public synchronized insert(int offset, String s) It is used to insert the specified string with this string at the
StringBuffer specified position. The insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
public synchronized replace(int startIndex, int It is used to replace the string from specified startIndex and
StringBuffer endIndex, String str) endIndex.
public synchronized delete(int startIndex, int It is used to delete the string from specified startIndex and
StringBuffer endIndex) endIndex.
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number of
characters.
public String substring(int beginIndex) It is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int It is used to return the substring from the specified beginIndex and
endIndex) endIndex.
[Link]
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
Output:
Hello Java
[Link]
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
Output:
HJavaello
[Link]
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
Output:
HJavalo
[Link]
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}
Output:
Hlo
[Link]
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);//prints olleH
}
}
Output:
olleH
[Link]
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
[Link]
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}
Output:
16
16
34
34
70
1.5.
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(int length) It creates an empty String Builder with the specified capacity as length.
Method Description
public StringBuilder append(String It is used to append the specified string with this string. The
s) append() method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int), insert(int, float), insert(int,
double) etc.
public StringBuilder replace(int It is used to replace the string from specified startIndex and
startIndex, int endIndex, String str) endIndex.
public StringBuilder delete(int It is used to delete the string from specified startIndex and endIndex.
startIndex, int endIndex)
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number of
characters.
public String substring(int It is used to return the substring from the specified beginIndex.
beginIndex)
public String substring(int It is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.
[Link]
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
Output:
Hello Java
[Link]
class StringBuilderExample2{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}
Output:
HJavaello
[Link]
class StringBuilderExample3{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
Output:
HJavalo
[Link]
class StringBuilderExample4{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}
Output:
Hlo
[Link]
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
[Link]();
[Link](sb);//prints olleH
}
}
Output:
olleH
[Link]
class StringBuilderExample6{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("Java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
[Link]
class StringBuilderExample7{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
[Link]([Link]());//default 16
[Link]("Hello");
[Link]([Link]());//now 16
[Link]("Java is my favourite language");
[Link]([Link]());//now (16*2)+2=34 i.e (oldcapacity*2)+2
[Link](10);//now no change
[Link]([Link]());//now 34
[Link](50);//now (34*2)+2
[Link]([Link]());//now 70
}
}
Output:
16
16
34
34
70
There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:
2) String is slow and consumes more memory when we StringBuffer is fast and consumes less
concatenate too many strings because every time it memory when we concatenate t strings.
creates new instance.
3) String class overrides the equals() method of Object class. StringBuffer class doesn't override the
So you can compare the contents of two strings by equals() method of Object class.
equals() method.
4) String class is slower while performing concatenation StringBuffer class is faster while performing
operation. concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
[Link]
Output:
The above code, calculates the time required for concatenating a string using the String class and
StringBuffer class.
[Link]
Output:
Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder
classes are mutable. There are many differences between StringBuffer and StringBuilder. The
StringBuilder class is introduced since JDK 1.5.
1) StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread safe.
means two threads can't call the methods of It means two threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
StringBuffer Example
[Link]
Output:
hellojava
StringBuilder Example
[Link]
Output:
hellojava
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
[Link]
Output:
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float,
Double etc. In short, all the wrapper classes and String class is immutable. We can also create
immutable class by creating final class that has final data members as the example given below:
In this example, we have created a final class named Employee. It has one final data member, a
parameterized constructor and getter method.
[Link]
{
[Link]=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
public class ImmutableDemo
{
public static void main(String ar[])
{
Employee e = new Employee("ABC123");
String s1 = [Link]();
[Link]("Pancard Number: " + s1);
}
}
Output:
o The instance variable of the class is final i.e. we cannot change the value of it after
creating an object.
o The class is final so we cannot create the subclass.
o There are no setter methods i.e. we have no option to change the value of the instance
variable.
If you want to represent any object as a string, toString() method comes into existence.
If you print any object, Java compiler internally invokes the toString() method on the object. So
overriding the toString() method, returns the desired output, it can be the state of an object etc.
depending on your implementation.
By overriding the toString() method of the Object class, we can return values of the object, so we
don't need to write much code.
[Link]
class Student{
int rollno;
String name;
String city;
Output:
Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects
but I want to print the values of these objects. Since Java compiler internally calls toString()
method, overriding this method will return the specified values. Let's understand it with the
example given below:
[Link]
class Student{
int rollno;
String name;
String city;
Output:
In the above program, Java compiler internally calls toString() method, overriding this method
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The [Link] class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.
Constructor Description
StringTokenizer(String str, String It creates StringTokenizer with specified string and delimiter.
delim)
StringTokenizer(String str, String It creates StringTokenizer with specified string, delimiter and returnValue.
delim, boolean returnValue) If return value is true, delimiter characters are considered to be tokens. If it
is false, delimiter characters serve to separate tokens.
Methods Description
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
Object nextElement() It is the same as nextToken() but its return type is Object.
[Link]
import [Link];
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:
my
name
is
khan
The above Java code, demonstrates the use of StringTokenizer class and its methods
hasMoreTokens() and nextToken().
[Link]
import [Link].*;
Output:
Next token is : my
Note: The StringTokenizer class is deprecated now. It is recommended to use the split() method of
the String class or the Pattern class that belongs to the [Link] package.
This method returns true if more tokens are available in the tokenizer String otherwise returns
false.
[Link]
import [Link];
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokenzer class
"," ");
/* Checks if the String has any more tokens */
while ([Link]())
{
[Link]([Link]());
}
}
Output:
Demonstrating
methods
from
StringTokenizer
class
The above Java program shows the use of two methods hasMoreTokens() and nextToken() of
StringTokenizer class.
This method returns the same value as hasMoreTokens() method of StringTokenizer class. The
only difference is this class can implement the Enumeration interface.
[Link]
import [Link];
public class StringTokenizer2
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");
while ([Link]())
{
[Link]([Link]());
}
}
}
Output:
Hello
everyone
I
am
a
Java
developer
nextElement() returns the next token object in the tokenizer String. It can implement
Enumeration interface.
[Link]
import [Link];
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Checks if the String has any more tokens */
while ([Link]())
{
/* Prints the elements from the String */
[Link]([Link]());
}
}
}
Output:
Hello
Everyone
Have
a
nice
day
This method calculates the number of tokens present in the tokenizer String.
[Link]
import [Link];
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
/* Prints the number of tokens present in the String */
[Link]("Total number of Tokens: "+[Link]());
}
}
Output:
The above Java code demonstrates the countTokens() method of StringTokenizer() class.
A list of top Java String FAQs (Frequently Asked Questions) or interview questions are given
below. These questions can be asked by the interviewer.
The equals() method matches content of the strings whereas == operator matches object or
reference of the strings.
Input:
this is javatpoint
Output:
tnioptavaj si siht
Input:
nitin
Output:
true
Input:
jatin
Output:
false
Input:
this is javatpoint
Output:
This Is Javatpoint
Input:
this is javatpoint
Output:
siht si tnioptavaj
Input:
this is javatpoint
Output:
tHIS iS jAVATPOINT
Input:
this is javatpoint
Output:
sIHT sI tNIOPTAVAJ
17) Java Program to check whether two Strings are anagram or not
18) Java program to find the percentage of uppercase, lowercase, digits and special
characters in a String
25) Java Program to reverse a given String with preserving the position of space
There are many ways to reverse String in Java. We can reverse String using StringBuffer,
StringBuilder, iteration etc. Let's see the ways to reverse String in Java.
1) By StringBuilder / StringBuffer
File: [Link]
File: [Link]
}
}
Output:
nahk si eman ym
lawsiaj oonos ma I
2) By Reverse Iteration
File: [Link]
File: [Link]
Output:
nahk si eman ym
lawsiaj oonos ma I