Java String
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.
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.
2) By new keyword
1.
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).
No.
1
Method
char charAt(int index)
Description
returns char value for the
particular index
int length()
args)
4
Object... args)
given locale
Java String
6
endIndex)
boolean contains(CharSequence s)
CharSequence... elements)
9
0
1
boolean isEmpty()
1
1
2
1
3
CharSequence new)
specified CharSequence
String trim()
6
1
matching regex
String split(String regex, int limit)
7
1
String intern()
8
1
9
2
0
index
int indexOf(int ch, int fromIndex)
Java String
index
2
1
2
String toLowerCase()
String toLowerCase(Locale l)
3
2
4
2
String toUpperCase(Locale l)
5
2
6
Do You Know ?
Why String objects are immutable?
What code is written by the compiler if you concat any string by + (string
concatenation operator)?
class Testimmutablestring{
Java String
2.
3.
4.
5.
6.
7.
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.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
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
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
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
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.
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.
Java String
1.
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.
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).
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.
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
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
String s="Sachin";
System.out.println(s.length());//6
6
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.
Java String
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.
Java String
5. System.out.println(sb);//prints HJavaello
6. }
7. }
Java String
7. }
Java String
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.
Description
public StringBuilder
append(String s)
public StringBuilder
public StringBuilder
and endIndex.
endIndex)
Java String
public StringBuilder
reverse()
public int capacity()
public void
ensureCapacity(int
given minimum.
minimumCapacity)
public char charAt(int
index)
position.
beginIndex)
beginIndex.
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
}
}
class A{
public static void main(String args[]){
Java String
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
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class A{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
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
}
}
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
StringBuffer
StringBuffer class is
mutable.
of Object class.
Java String
Time taken by Concating with String: 578ms
Time taken by Concating with
StringBuffer: 0ms
}
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 simultaneously.
StringBuilder simultaneously.
StringBuilder.
StringBuffer.
StringBuffer Example
hellojava
1.
2.
3.
4.
5.
6.
7.
StringBuilder Example
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.
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:
There is no setter methods i.e. we have no option to change the value of the
instance variable.
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:
There is no setter methods i.e. we have no option to change the value of the
instance variable.
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.
int rollno;
3.
String name;
4.
String city;
5.
6.
7.
this.rollno=rollno;
8.
this.name=name;
9.
this.city=city;
10. }
11.
12. public static void main(String args[]){
13.
14.
15.
16.
Java String
17.
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:
int rollno;
3.
String name;
4.
String city;
5.
6.
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.
17.
18.
Java String
19.
20.
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
Description
Description
boolean hasMoreTokens()
String nextToken()
String nextToken(String
delim)
Java String
Object nextElement()
int countTokens()
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.
4.
5.
while (st.hasMoreTokens()) {
6.
System.out.println(st.nextToken());
7.
8.
}
}
9. }
Output:my
name
is
khan
6.
7.
8.
Java String
9.
10.}
Output:Next token is : my