Java String
Java String provides a lot of concepts that can be performed on a string such as
compare, concat, equals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents sequence of char values.
An array of characters works same as java string. For example:
1.
2.
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
1.
String s="javatpoint";
The java.lang.String class implements Serializable, Comparable and CharSequence
interfaces.
The java String is immutable i.e. it cannot be changed but a new instance is created.
For mutable class, you can use StringBuffer and StringBuilder class.
We will discuss about immutable string later. Let's first understand what is string in
java and how to create the string object.
What is String in java
Generally, string is a sequence of characters. But in java, string is an object that
represents a sequence of characters. String class is used to create string object.
How to create String object?
There are two ways to create 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";
Java String
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
string doesn't exist in the pool, a new string instance is created and placed in the
pool. For example:
1.
2.
String s1="Welcome";
String s2="Welcome";//will not create 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, so it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant
pool.
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).
2) By new keyword
1.
String s=new String("Welcome");//creates two objects and one reference variabl
Java String
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).
Java String Example
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
java
strings
example
Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
No.
1
Method
char charAt(int index)
Description
returns char value for the
particular index
int length()
returns string length
static String format(String format, Object...
returns formatted string
args)
4
static String format(Locale l, String format,
returns formatted string with
Object... args)
given locale
String substring(int beginIndex)
returns substring for given
begin index
Java String
6
String substring(int beginIndex, int
returns substring for given
endIndex)
begin index and end index
boolean contains(CharSequence s)
returns true or false after
matching the sequence of
char value
static String join(CharSequence delimiter,
returns a joined string
CharSequence... elements)
9
static String join(CharSequence delimiter,
returns a joined string
Iterable<? extends CharSequence>
elements)
1
boolean equals(Object another)
0
1
checks the equality of string
with object
boolean isEmpty()
checks if string is empty
String concat(String str)
concatinates specified string
String replace(char old, char new)
replaces all occurrences of
1
1
2
1
3
specified char value
String replace(CharSequence old,
replaces all occurrences of
CharSequence new)
specified CharSequence
String trim()
returns trimmed string
omitting leading and trailing
spaces
String split(String regex)
6
1
matching regex
String split(String regex, int limit)
7
1
returns splitted string
returns splitted string
matching regex and limit
String intern()
returns interned string
int indexOf(int ch)
returns specified char value
8
1
9
2
0
index
int indexOf(int ch, int fromIndex)
returns specified char value
index starting with given
Java String
index
2
int indexOf(String substring)
1
2
returns specified substring
index
int indexOf(String substring, int fromIndex)
returns specified substring
index starting with given
index
String toLowerCase()
returns string in lowercase.
String toLowerCase(Locale l)
returns string in lowercase
3
2
4
2
using specified locale.
String toUpperCase()
returns string in uppercase.
String toUpperCase(Locale l)
returns string in uppercase
5
2
6
using specified locale.
Do You Know ?
Why String objects are immutable?
How to create an immutable class?
What is string constant pool?
What code is written by the compiler if you concat any string by + (string
concatenation operator)?
What is the difference between StringBuffer and StringBuilder class?
Immutable String in Java
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 immutability concept by the example given below:
1.
class Testimmutablestring{
Java String
2.
3.
4.
5.
6.
7.
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed
but a new object is created with sachintendulkar. 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 explicitely assign it to the reference variable, it will refer to "Sachin
Tendulkar" object.For example:
1.
2.
3.
4.
5.
6.
7.
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object
is not modified.
Java String
Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference
variables,all referes to one object "sachin".If one reference variable changes the
value of the object, it will be affected to all the reference variables. That is why string
objects are immutable in java.
Java String
Java String compare
We can compare string in java 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 in java:
1. By equals() method
2. By = = operator
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares
values of string for equality. String class provides two methods:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
public boolean equals(Object another) compares this string to the
specified object.
public boolean equalsIgnoreCase(String another) compares this String to
another string, ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output:true
true
false
1.
2.
3.
4.
5.
6.
7.
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
Java String
8.
9.
}
}
Output:false
true
2) String compare by == operator
The = = operator compares references not values.
1.
2.
3.
4.
5.
6.
7.
class Teststringcomparison3{
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 no
npool)
8.
}
9.
}
Output:true
false
3) String compare by compareTo() method
The String compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second
string.
Suppose s1 and s2 are two string variables. If:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
s1 == s2 :0
s1 > s2
:positive value
s1 < s2
:negative value
class Teststringcomparison4{
public static void main(String args[]){
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 )
}
}
Output:0
1
-1
Java String
String Concatenation in Java
In java, string concatenation forms a new string that is the combination of multiple
strings. There are two ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method
1) String Concatenation by + (string concatenation)
operator
Java string concatenation operator (+) is used to add strings. For Example:
1.
2.
3.
4.
5.
6.
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output:Sachin Tendulkar
The Java compiler transforms above code to this:
1.
String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
In java, String concatenation is implemented through the StringBuilder (or
StringBuffer) class and its 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 concat not only string but primitive values also. For
Example:
1.
2.
3.
4.
5.
6.
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
}
}
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current
string. Syntax:
Java String
1.
public String concat(String another)
Let's see the example of String concat() method.
1.
2.
3.
4.
5.
6.
7.
8.
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Sachin Tendulkar
Java String
Substring in Java
A part of string is called substring. In other words, substring is a subset of another
string. In case of substring startIndex is inclusive and endIndex is exclusive.
Note: Index starts from 0.
You can get substring from the given string object by one of the two methods:
1. public String substring(int startIndex): This method returns new String
object containing the substring of the given string from specified startIndex
(inclusive).
2. public String substring(int startIndex, int endIndex): This method
returns new String object containing the substring of the given string from
specified startIndex to endIndex.
In case of string:
o
startIndex: inclusive
endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1.
2.
String s="hello";
System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is
exclusive).
Example of java substring
1.
2.
3.
4.
5.
6.
7.
public class TestSubstring{
public static void main(String args[]){
String s="Sachin Tendulkar";
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
Tendulkar
Sachin
Java String
Java String class methods
The java.lang.String class provides a lot of methods to work on string. By the help of
these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.
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.
Let's see the important methods of String class.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and
string toLowerCase() method into lowercase letter.
1.
2.
3.
4.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
SACHIN
sachin
Sachin
Java String trim() method
The string trim() method eliminates white spaces before and after string.
1.
2.
3.
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin
Sachin
Sachin
Java String startsWith() and endsWith() method
1.
2.
3.
String s="Sachin";
System.out.println(s.startsWith("Sa"));//true
System.out.println(s.endsWith("n"));//true
true
true
Java String
Java String charAt() method
The string charAt() method returns a character at specified index.
1.
2.
3.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
S
h
Java String length() method
The string length() method returns length of the string.
1.
2.
String s="Sachin";
System.out.println(s.length());//6
6
Java String intern() method
A pool of strings, initially empty, is maintained privately by the class String.
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.
1.
2.
3.
String s=new String("Sachin");
String s2=s.intern();
System.out.println(s2);//Sachin
Sachin
Java String valueOf() method
The string valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into string.
1.
2.
3.
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
Output:
1010
Java String
Java String replace() method
The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.
1.
2.
String s1="Java is a programming language. Java is a platform. Java is an Island.
";
String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java
" to "Kava"
3.
System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.
Java String
Java StringBuffer class
Java StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.
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.
Important Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with the initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity
as length.
Important methods of StringBuffer class
1. public synchronized StringBuffer append(String s): is used to append the specified
string with this string. The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
2. public synchronized StringBuffer insert(int offset, String s): is used to insert the
specified string with this string at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
3. public synchronized StringBuffer replace(int startIndex, int endIndex, String
str): is used to replace the string from specified startIndex and endIndex.
4. public synchronized StringBuffer delete(int startIndex, int endIndex): is used to
delete the string from specified startIndex and endIndex.
5. public synchronized StringBuffer reverse(): is used to reverse the string.
6. public int capacity(): is used to return the current capacity.
7. public void ensureCapacity(int minimumCapacity): is used to ensure the capacity
at least equal to the given minimum.
8. public char charAt(int index): is used to return the character at the specified
position.
9. public int length(): is used to return the length of the string i.e. total number of
characters.
Java String
10. public String substring(int beginIndex): is used to return the substring from the
specified beginIndex.
11. public String substring(int beginIndex, int endIndex): is used to return the
substring from the specified beginIndex and endIndex.
What is mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
1) StringBuffer append() method
The append() method concatenates the given argument with this string.
1. class A{
2. public static void main(String args[]){
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. }
2) StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
Java String
5. System.out.println(sb);//prints HJavaello
6. }
7. }
3) StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
1. class A{
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. }
4) StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
Java String
7. }
5) StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
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. }
10. }
Java String
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
1. class A{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer();
4. System.out.println(sb.capacity());//default 16
5. sb.append("Hello");
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. }
Java String
Java StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java
StringBuilder class is same as StringBuffer class except that it is non-synchronized. It
is available since JDK 1.5.
Important Constructors of StringBuilder class
1. StringBuilder(): creates an empty string Builder with the initial capacity of
16.
2. StringBuilder(String str): creates a string Builder with the specified string.
3. StringBuilder(int length): creates an empty string Builder with the specified
capacity as length.
Important methods of StringBuilder class
Method
Description
public StringBuilder
is used to append the specified string with this
append(String s)
string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.
public StringBuilder
is used to insert the specified string with this string
insert(int offset, String s)
at the 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
is used to replace the string from specified
replace(int startIndex, int
startIndex and endIndex.
endIndex, String str)
public StringBuilder
is used to delete the string from specified startIndex
delete(int startIndex, int
and endIndex.
endIndex)
Java String
public StringBuilder
is used to reverse the string.
reverse()
public int capacity()
is used to return the current capacity.
public void
is used to ensure the capacity at least equal to the
ensureCapacity(int
given minimum.
minimumCapacity)
public char charAt(int
is used to return the character at the specified
index)
position.
public int length()
is used to return the length of the string i.e. total
number of characters.
public String substring(int
is used to return the substring from the specified
beginIndex)
beginIndex.
public String substring(int
is used to return the substring from the specified
beginIndex, int endIndex)
beginIndex and endIndex.
Java StringBuilder Examples
Let's see the examples of different methods of StringBuilder class.
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this string.
1.
2.
3.
4.
5.
6.
7.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at the given
position.
1.
2.
class A{
public static void main(String args[]){
Java String
3.
4.
5.
6.
7.
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.
1.
2.
3.
4.
5.
6.
7.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.
1.
2.
3.
4.
5.
6.
7.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.
1.
2.
3.
4.
5.
6.
7.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuilder capacity() method
The capacity() method of StringBuilder class returns the current capacity of the
Builder. The default capacity of the Builder is 16. If the number of character increases
from its current capacity, it increases the capacity by (oldcapacity*2)+2. For example
if your current capacity is 16, it will be (16*2)+2=34.
Java String
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
7) StringBuilder ensureCapacity() method
The ensureCapacity() method of StringBuilder class ensures that the given capacity is
the minimum to the current capacity. If it is greater than the current capacity, it
increases the capacity by (oldcapacity*2)+2. For example if your current capacity is
16, it will be (16*2)+2=34.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Java String
Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences
between String and StringBuffer are given below:
No. String
1
String class is immutable.
StringBuffer
StringBuffer class is
mutable.
String is slow and consumes more memory
StringBuffer is fast and
when you concat too many strings because
consumes less memory
every time it creates new instance.
when you cancat strings.
String class overrides the equals() method
StringBuffer class doesn't
of Object class. So you can compare the
override the equals() method
contents of two strings by equals() method.
of Object class.
Performance Test of String and StringBuffer
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
public class ConcatTest{
public static String concatWithString() {
String t = "Java";
for (int i=0; i<10000; i++){
t = t + "Tpoint";
}
return t;
}
public static String concatWithStringBuffer(){
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
return sb.toString();
}
public static void main(String[] args){
long startTime = System.currentTimeMillis();
concatWithString();
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.
}
Java String
Time taken by Concating with String: 578ms
Time taken by Concating with
StringBuffer: 0ms
String and StringBuffer HashCode Test
As you can see in the program given below, String returns new hashcode value when
you concat string but StringBuffer returns same.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
public class InstanceTest{
public static void main(String args[]){
System.out.println("Hashcode test of String:");
String str="java";
System.out.println(str.hashCode());
str=str+"tpoint";
System.out.println(str.hashCode());
System.out.println("Hashcode test of StringBuffer:");
StringBuffer sb=new StringBuffer("java");
System.out.println(sb.hashCode());
sb.append("tpoint");
System.out.println(sb.hashCode());
}
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462
Java String
Difference between StringBuffer and
StringBuilder
There are many differences between StringBuffer and StringBuilder. A list of
differences between StringBuffer and StringBuilder are given below:
No. StringBuffer
1.
2.
3.
4.
5.
6.
7.
StringBuilder
StringBuffer is synchronized i.e.
StringBuilder is non-synchronized i.e.
thread safe. It means two threads
not thread safe. It means two
can't call the methods of
threads can call the methods of
StringBuffer simultaneously.
StringBuilder simultaneously.
StringBuffer is less efficient than
StringBuilder is more efficient than
StringBuilder.
StringBuffer.
StringBuffer Example
public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");
buffer.append("java");
System.out.println(buffer);
}
}
hellojava
1.
2.
3.
4.
5.
6.
7.
StringBuilder Example
public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
}
}
hellojava
Java String
Performance Test of StringBuffer and StringBuilder
Let's see the code to check the performance of StringBuffer and StringBuilder classes.
1.
2.
3.
4.
5.
6.
7.
8.
public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMil
lis() - startTime) + "ms");
9.
startTime = System.currentTimeMillis();
10.
StringBuilder sb2 = new StringBuilder("Java");
11.
for (int i=0; i<10000; i++){
12.
sb2.append("Tpoint");
13.
}
14.
System.out.println("Time taken by StringBuilder: " + (System.currentTimeM
illis() - startTime) + "ms");
15.
}
16.
}
Java String
How to create Immutable class?
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 have final data members
as the example given below:
Example to create Immutable class
In this example, we have created a final class named Employee. It have one final
datamember, a parameterized constructor and getter method.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
The above class is immutable because:
The instance variable of the class is final i.e. we cannot change the value of it
after creating an object.
The class is final so we cannot create the subclass.
There is no setter methods i.e. we have no option to change the value of the
instance variable.
These points makes this class as immutable.
Java String
How to create Immutable class?
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 have final data members
as the example given below:
Example to create Immutable class
In this example, we have created a final class named Employee. It have one final
datamember, a parameterized constructor and getter method.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
public final class Employee{
final String pancardNumber;
public Employee(String pancardNumber){
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
The above class is immutable because:
The instance variable of the class is final i.e. we cannot change the value of it
after creating an object.
The class is final so we cannot create the subclass.
There is no setter methods i.e. we have no option to change the value of the
instance variable.
These points makes this class as immutable.
Java String
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
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. depends on your implementation.
Advantage of Java toString() method
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.
Understanding problem without toString() method
Let's see the simple code that prints reference.
1. class Student{
2.
int rollno;
3.
String name;
4.
String city;
5.
6.
Student(int rollno, String name, String city){
7.
this.rollno=rollno;
8.
this.name=name;
9.
this.city=city;
10. }
11.
12. public static void main(String args[]){
13.
Student s1=new Student(101,"Raj","lucknow");
14.
Student s2=new Student(102,"Vijay","ghaziabad");
15.
16.
System.out.println(s1);//compiler writes here s1.toString()
Java String
17.
System.out.println(s2);//compiler writes here s2.toString()
18. }
19.}
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:
Example of Java toString() method
Now let's see the real example of toString() method.
1. class Student{
2.
int rollno;
3.
String name;
4.
String city;
5.
6.
Student(int rollno, String name, String city){
7.
this.rollno=rollno;
8.
this.name=name;
9.
this.city=city;
10. }
11.
12. public String toString(){//overriding the toString() method
13. return rollno+" "+name+" "+city;
14. }
15. public static void main(String args[]){
16.
Student s1=new Student(101,"Raj","lucknow");
17.
Student s2=new Student(102,"Vijay","ghaziabad");
18.
Java String
19.
System.out.println(s1);//compiler writes here s1.toString()
20.
System.out.println(s2);//compiler writes here s2.toString()
21. }
22.}
Output:101 Raj lucknow
102 Vijay ghaziabad
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way
to break string.
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.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
Constructor
Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str, creates StringTokenizer with specified string and
String delim)
delimeter.
creates StringTokenizer with specified string,
StringTokenizer(String str, delimeter and returnValue. If return value is true,
String delim, boolean
delimiter characters are considered to be tokens. If it
returnValue)
is false, delimiter characters serve to separate
tokens.
Methods of StringTokenizer class
The 6 useful methods of StringTokenizer class are as follows:
Public method
Description
boolean hasMoreTokens()
checks if there is more tokens available.
String nextToken()
returns the next token from the StringTokenizer
object.
String nextToken(String
delim)
returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Java String
Object nextElement()
same as nextToken() but its return type is Object.
int countTokens()
returns the total number of tokens.
Simple example of StringTokenizer class
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.
1. import java.util.StringTokenizer;
2. public class Simple{
3.
public static void main(String args[]){
4.
StringTokenizer st = new StringTokenizer("my name is khan"," ");
5.
while (st.hasMoreTokens()) {
6.
System.out.println(st.nextToken());
7.
8.
}
}
9. }
Output:my
name
is
khan
Example of nextToken(String delim) method of StringTokenizer class
1. import java.util.*;
2.
3. public class Test {
4.
5.
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
6.
7.
// printing next token
8.
System.out.println("Next token is : " + st.nextToken(","));
Java String
9.
10.}
Output:Next token is : my
StringTokenizer class is deprecated now. It is recommended to use split() method
of String class or regex (Regular Expression).