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:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. 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.
The java.lang.String class implements Serializable, Comparable and
CharSequence interfaces.Google launches Liv Caption on Chrome
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.
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. The java.lang.String class is used
to create a string object.
How to create a 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";
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".
Why Java uses the concept of String literal?
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
1. String s=new String("Welcome");//creates two objects and one referen
ce variableIn 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).
Java String Example
StringExample.java
1. public class StringExample{
2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10.}}
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.
Java String class methods
The java.lang.String class provides many useful methods to perform
operations on sequence of char values.
No Method Description
.
1 char charAt(int index) It returns char value for the
particular index
2 int length() It returns string length
3 static String format(String format, Object... It returns a formatted string.
args)
4 static String format(Locale l, String format, It returns formatted string with
Object... args) given locale.
5 String substring(int beginIndex) It returns substring for given
begin index.
6 String substring(int beginIndex, int endIndex) It returns substring for given
begin index and end index.
7 boolean contains(CharSequence s) It returns true or false after
matching the sequence of char
value.
8 static String join(CharSequence delimiter, It returns a joined string.
CharSequence... elements)
9 static String join(CharSequence delimiter, It returns a joined string.
Iterable<? extends CharSequence> elements)
10 boolean equals(Object another) It checks the equality of string
with the given object.
11 boolean isEmpty() It checks if string is empty.
12 String concat(String str) It concatenates the specified
string.
13 String replace(char old, char new) It replaces all occurrences of the
specified char value.
14 String replace(CharSequence old, It replaces all occurrences of the
CharSequence new) specified CharSequence.
15 static String equalsIgnoreCase(String another) It compares another string. It
doesn't check case.
16 String[] split(String regex) It returns a split string matching
regex.
17 String[] split(String regex, int limit) It returns a split string matching
regex and limit.
18 String intern() It returns an interned string.
19 int indexOf(int ch) It returns the specified char value
index.
20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
21 int indexOf(String substring) It returns the specified substring
index.
22 int indexOf(String substring, int fromIndex) It returns the specified substring
index starting with given index.
23 String toLowerCase() It returns a string in lowercase.
24 String toLowerCase(Locale l) It returns a string in lowercase
using specified locale.
25 String toUpperCase() It returns a string in uppercase.
26 String toUpperCase(Locale l) It returns a string in uppercase
using specified locale.
27 String trim() It removes beginning and ending
spaces of this string.
28 static String valueOf(int value) It converts given type into string.
It is an overloaded method.
Immutable String in Java
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:
Testimmutablestring.javaM.3KOOPs Concepts in Java
1. class Testimmutablestring{
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 immutabl
e objects
6. }
7. }
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, 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
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. }
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still
Sachin object is not modified.
Java StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects.
The StringBuffer class in Java is the 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
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
StringBuffer(String str) It creates a String buffer with the specified string..
StringBuffer(int It creates an empty String buffer with the specified capacity as
capacity) length.
Important methods of StringBuffer class
Modifier and Method Description
Type
public append(String s) It is used to append the specified string with this
synchronized string. The append() method is overloaded like
StringBuffer append(char), append(boolean), append(int),
append(float), append(double) etc.
public insert(int offset, It is used to insert the specified string with this
synchronized String s) string at the specified position. The insert()
StringBuffer method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
public replace(int It is used to replace the string from specified
synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex, String str)
public delete(int startIndex, It is used to delete the string from specified
synchronized int endIndex) startIndex and endIndex.
StringBuffer
public reverse() is used to reverse the string.
synchronized
StringBuffer
public int capacity() It is used to return the current capacity.
public void ensureCapacity(int It is used to ensure the capacity at least equal to
minimumCapacity) the given 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 It is used to return the substring from the
beginIndex) specified beginIndex.
public String substring(int It is used to return the substring from the
beginIndex, int specified beginIndex and endIndex.
endIndex)
What is a mutable String?
A String that can be modified or changed is known as mutable String.
StringBuffer and StringBuilder classes are used for creating mutable strings.
1) StringBuffer Class append() Method
The append() method concatenates the given argument with this String.
StringBufferExample.java $44 billion Twitter takeover
1. class StringBufferExample{
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. }
Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given
position.
StringBufferExample2.java
1. class StringBufferExample2{
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. }
Output:
HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified
beginIndex and endIndex.
StringBufferExample3.java
1. class StringBufferExample3{
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. }
Output:
HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the
specified beginIndex to endIndex.
StringBufferExample4.java
1. class StringBufferExample4{
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. }
7. }
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
1. class StringBufferExample5{
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. }
Output:
olleH
6) StringBuffer capacity() Method
The capacity() method of the 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.
StringBufferExample6.java
1. class StringBufferExample6{
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.}
Output:
16
16
34
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of the 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.
StringBufferExample7.java
1. class StringBufferExample7{
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.}
Output:
16
16
34
34
70
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
Constructor Description
StringBuilder() It creates an empty String Builder with the initial capacity of 16.
StringBuilder(String It creates a String Builder with the specified string.
str)
StringBuilder(int It creates an empty String Builder with the specified capacity as
length) length.
Important methods of StringBuilder class
Method Description
public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public StringBuilder It is used to insert the specified string with this string at the
insert(int 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 It is used to replace the string from specified startIndex and
replace(int startIndex, int endIndex.
endIndex, String str)
public StringBuilder It is used to delete the string from specified startIndex and
delete(int startIndex, int endIndex.
endIndex)
public StringBuilder It is used to reverse the string.
reverse()
public int capacity() It is used to return the current capacity.
public void It is used to ensure the capacity at least equal to the given
ensureCapacity(int minimum.
minimumCapacity)
public char charAt(int It is used to return the character at the specified position.
index)
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, 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.
StringBuilderExample.java
1. class StringBuilderExample{
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. }
Output:
Hello Java
2) StringBuilder insert() method
The StringBuilder insert() method inserts the given string with this string at
the given position.
StringBuilderExample2.java
1. class StringBuilderExample2{
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. }
Output:
HJavaello
3) StringBuilder replace() method
The StringBuilder replace() method replaces the given string from the
specified beginIndex and endIndex.
StringBuilderExample3.java
1. class StringBuilderExample3{
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. }
Output:
HJavalo
4) StringBuilder delete() method
The delete() method of StringBuilder class deletes the string from the
specified beginIndex to endIndex.
StringBuilderExample4.java
1. class StringBuilderExample4{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
Output:
Hlo
5) StringBuilder reverse() method
The reverse() method of StringBuilder class reverses the current string.
StringBuilderExample5.java
1. class StringBuilderExample5{
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. }
Output:
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.
StringBuilderExample6.java
1. class StringBuilderExample6{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
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.}
Output:
16
16
34
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.
StringBuilderExample7.java
1. class StringBuilderExample7{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder();
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.}
Output:
16
16
34
34
70