Java String
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 CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by
using these three classes.
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.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
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";
2. String s2="Welcome";//It doesn't create a new instance
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".
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
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).
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.
1 char charAt(int index) It returns char value for the particular index
6 String substring(int It returns substring for given begin index and end index.
beginIndex, int endIndex)
7 boolean It returns true or false after matching the sequence of char
contains(CharSequence s) value.
10 boolean equals(Object It checks the equality of string with the given object.
another)
13 String replace(char old, char It replaces all occurrences of the specified char value.
new)
17 String[] split(String regex, int It returns a split string matching regex and limit.
limit)
20 int indexOf(int ch, int It returns the specified char value index starting with given
fromIndex) index.
22 int indexOf(String substring, It returns the specified substring index starting with given
int fromIndex) index.
28 static String valueOf(int value) It converts given type into string. It is an overloaded method.
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:
Testimmutablestring.java
Output:
1. class Testimmutablestring{
Sachin
2. public static void main(String args[]){
3. String s="Sachin";
4. s.concat(" Tendulkar");//concat() method appends the string at the end
5. System.out.println(s);//will print Sachin because strings are immutable objects
6. }
7. }
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:
Testimmutablestring1.java Output:
Sachin Tendulkar
1. class Testimmutablestring1{
2. public static void main(String args[]){
3. String s="Sachin";
4. s=s.concat(" Tendulkar");
5. System.out.println(s);
6. }
7. }
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.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
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.
Teststringcomparison1.java
1. class Teststringcomparison1{
2. public static void main(String args[]){ Output:
3. String s1="Sachin"; true
true
4. String s2="Sachin"; false
5. String s3=new String("Sachin");
6. String s4="Saurav";
7. System.out.println(s1.equals(s2));//true
8. System.out.println(s1.equals(s3));//true
9. System.out.println(s1.equals(s4));//false
10. }
11. }
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.
Teststringcomparison2.java
1. class Teststringcomparison2{
2. public static void main(String args[]){
Output:
3. String s1="Sachin";
false
4. String s2="SACHIN";
true
5.
6. System.out.println(s1.equals(s2));//false
7. System.out.println(s1.equalsIgnoreCase(s2));//true
8. }
9. }
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
The == operator compares references not values.
Teststringcomparison3.java
Output:
1. class Teststringcomparison3{
true
2. public static void main(String args[]){ false
3. String s1="Sachin";
4. String s2="Sachin";
5. String s3=new String("Sachin");
6. System.out.println(s1==s2);//true (because both refer to same instance)
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
8. }
9. }
1. class Teststringcomparison4{
Output:
2. public static void main(String args[]){
0
3. String s1="Sachin"; 1
4. String s2="Sachin"; -1
5. String s3="Ratan";
6. System.out.println(s1.compareTo(s2));//0
7. System.out.println(s1.compareTo(s3));//1(because s1>s3)
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
9. }
10. }
TestStringConcatenation1.java
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:
TestStringConcatenation2.java
1. class TestStringConcatenation2{
Output:
2. public static void main(String args[]){
80Sachin4040
3. String s=50+30+"Sachin"+40+40;
4. System.out.println(s);//80Sachin4040
5. }
6. }
Note: After a string literal, all the + will be treated as string concatenation operator.
The above Java program, concatenates two String objects s1 and s2 using concat() method and stores
the result into s3 object.
StrFormat.java
Output:
1. public class StrFormat
2. { Hello World
3. /* Driver Code */
4. public static void main(String args[])
5. {
6. String s1 = new String("Hello"); //String 1
7. String s2 = new String(" World"); //String 2
8. String s = String.format("%s%s",s1,s2); //String 3 to store the result
9. System.out.println(s.toString()); //Displays result
10. }
11. }
StrJoin.java:
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.
Output:
Here, a list of String array is declared. And a String object str stores the result
of Collectors.joining() 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.
1. String s="hello";
2. System.out.println(s.substring(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).
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.
Stringoperation2.java 1. {
2. String s=" Sachin ";
1. public class Stringoperation2 3. System.out.println(s);// Sachin
2. { 4. System.out.println(s.trim());//Sachin
3. public static void main(String ar[]) 5. }
Output:
6. }
Sachin
Sachin
Stringoperation3.java 1. {
2. String s="Sachin";
1. public class Stringoperation3 3. System.out.println(s.startsWith("Sa"));//true
2. { 4. System.out.println(s.endsWith("n"));//true
3. public static void main(String ar[]) 5. }
Output:
6. }
true
true
Stringoperation4.java 1. {
2. String s="Sachin";
1. public class Stringoperation4
3. System.out.println(s.charAt(0));//S
2. {
4. System.out.println(s.charAt(3));//h
3. public static void main(String ar[])
5. }
Output:
6. }
S
h
Stringoperation5.java
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.
Stringoperation6.java
2. { 4. }
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 append(String s) It is used to append the specified string with this string. The
synchronized append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float), append(double)
etc.
public insert(int offset, String s) It is used to insert the specified string with this string at the
synchronized specified position. The insert() method is overloaded like
StringBuffer insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public replace(int startIndex, int It is used to replace the string from specified startIndex and
synchronized endIndex, String str) endIndex.
StringBuffer
public delete(int startIndex, int It is used to delete the string from specified startIndex and
synchronized endIndex) endIndex.
StringBuffer
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, It is used to return the substring from the specified beginIndex
int endIndex) and endIndex.
StringBufferExample.java
1. class StringBufferExample{ Output:
2. public static void main(String args[]){
Hello Java
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
StringBufferExample2.java
Output:
1. class StringBufferExample2{ HJavaello
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
StringBufferExample3.java
Output:
1. class StringBufferExample3{ HJavalo
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
StringBufferExample4.java Output:
StringBufferExample5.java
1. class StringBufferExample5{
Output:
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello"); olleH
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
StringBufferExample6.java
1. class StringBufferExample7{
Output:
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer(); 16
16
4. System.out.println(sb.capacity());//default 16 34
34
5. sb.append("Hello"); 70
6. System.out.println(sb.capacity());//now 16
7. sb.append("java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. sb.ensureCapacity(10);//now no change
10. System.out.println(sb.capacity());//now 34
11. sb.ensureCapacity(50);//now (34*2)+2
12. System.out.println(sb.capacity());//now 70
13. }
14. }
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 It is used to append the specified string with this string. The append() method
append(String s) 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 specified position.
offset, String s) 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 endIndex.
startIndex, int endIndex, String
str)
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 endIndex.
beginIndex, int endIndex)
StringBuilderExample.java
Output:
1. class StringBuilderExample{ Hello Java
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
StringBuilderExample2.java
Output:
1. class StringBuilderExample2{
HJavaello
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
StringBuilderExample3.java
Output:
1. class StringBuilderExample3{
HJavalo
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
StringBuilderExample4.java
1. class StringBuilderExample4{
Output:
2. public static void main(String args[]){
Hlo
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
StringBuilderExample5.java
Output:
1. class StringBuilderExample5{
olleH
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
StringBuilderExample6.java
1. class StringBuilderExample6{ 1. }
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder(); Output:
4. System.out.println(sb.capacity());//default 16 16
5. sb.append("Hello"); 16
34
6. System.out.println(sb.capacity());//now 16
7. sb.append("Java is my favourite language");
8. System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
9. }
StringBuilderExample7.java
1. class StringBuilderExample7{
2. public static void main(String args[]){ Output:
3. StringBuilder sb=new StringBuilder();
16
4. System.out.println(sb.capacity());//default 16 16
34
5. sb.append("Hello"); 34
6. System.out.println(sb.capacity());//now 16 70
2) String is slow and consumes more memory when we StringBuffer is fast and consumes less
concatenate too many strings because every time it creates memory when we concatenate t strings.
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() equals() method of Object class.
method.
4) String class is slower while performing concatenation StringBuffer class is faster while
operation. performing concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
15. }
16. public static void main(String[] args){
17. long startTime = System.currentTimeMillis();
18. concatWithString();
19. System.out.println("Time taken by Concating with String: "+(System.currentTimeMillis()-
startTime)+"ms");
20. startTime = System.currentTimeMillis();
21. concatWithStringBuffer();
22. System.out.println("Time taken by Concating with StringBuffer: "+(System.currentTimeMillis()-
startTime)+"ms");
23. }
24. }
The above code, calculates the time required for concatenating a string using the String class and
StringBuffer class.
1) StringBuffer is synchronized i.e. thread safe. It StringBuilder is non-synchronized i.e. not thread
means two threads can't call the methods of safe. 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
BufferTest.java
6. System.out.println(buffer);
7. }
8. }
StringBuilder Example
BuilderTest.java
ConcatTest.java
13. sb2.append("Tpoint");
ImmutableDemo.java
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 is no setter methods i.e. we have no option to change the value of the instance variable.
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.
HTML Tutorial
Understanding problem without toString() method
Let's see the simple code that prints reference.
Student.java
1. public static void main(String args[]){
2. Student s1=new Student(101,"Raj","lucknow
1. class Student{
");
2. int rollno;
3. Student s2=new Student(102,"Vijay","ghaziabad
3. String name;
");
4. String city;
4.
5.
5. System.out.println(s1);//compiler writes here s1.t
6. Student(int rollno, String name, String city){
oString()
7. this.rollno=rollno;
6. System.out.println(s2);//compiler writes here
8. this.name=name;
s2.toString()
9. this.city=city;
7. }
10. }
8. }
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:
Student.java
1. class Student{
1. return rollno+" "+name+" "+city;
2. int rollno;
2. }
3. String name;
3. public static void main(String args[]){
4. String city;
4. Student s1=new Student(101,"Raj","lucknow");
5. Student(int rollno, String name, String city){
5. Student s2=new Student(102,"Vijay","ghaziabad");
6. this.rollno=rollno;
6.
7. this.name=name;
7. System.out.println(s1);//compiler writes here s1.toSt
8. this.city=city;
ring()
9. }
8. System.out.println(s2);//compiler writes here s2.toString(
10.
)
11. public String toString()
9. }
12. {//overriding the toString() method
10. }
Output:
In the above program, Java compiler internally calls toString() method, overriding this method will
return the specified values of s1 and s2 objects of Student class.
StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer
The java.util.StringTokenizer 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. If
delim, boolean returnValue) 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.
Simple.java
1. while (st.hasMoreTokens()) {
1. import java.util.StringTokenizer; 2. System.out.println(st.nextToken());
2. public class Simple{ 3. }
3. public static void main(String args[]){ 4. }
4. 5. }
5. StringTokenizer st = new StringTokenizer("my name is khan"," ");
Output:
my
name
is
khan
The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens()
and nextToken().
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 java.util.regex package.
Output:
Demonstrating
methods
from
StringTokenizer
class
The above Java program shows the use of two methods hasMoreTokens() and nextToken() of
StringTokenizer class.
Example of hasMoreElements() method of the 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.
1. while (st.hasMoreElements())
StringTokenizer2.java
2. {
1. import java.util.StringTokenizer; 3. System.out.println(st.nextToken());
2. public class StringTokenizer2 4. }
3. { 5. }
4. public static void main(String args[]) 6. }
5. {
6. StringTokenizer st = new StringTokenizer("Hello everyone I am a Java developer"," ");
Output:
Hello
everyone
I
am
a
Java
developer
StringTokenizer4.java
1. import java.util.StringTokenizer;
2. public class StringTokenizer3
3. {
4. /* Driver Code */
5. public static void main(String args[])
6. {
7. /* StringTokenizer object */
8. StringTokenizer st = new StringTokenizer("Hello Everyone Have a nice day"," ");
9. /* Prints the number of tokens present in the String */
10. System.out.println("Total number of Tokens: "+st.countTokens());
11. }
12. }
Output:
The above Java code demonstrates the countTokens() method of StringTokenizer() class.