Java String: Java String Class Provides A Lot of Methods To Perform Operations On String Such As
Java String: Java String Class Provides A Lot of Methods To Perform Operations On String Such As
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 string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
CharSequence Interface
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first.
If the string already exists in the pool, a reference to the pooled instance is
returned. If 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";//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
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 heap(non pool).
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);
}}
Output
java
strings
example
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:
class Testimmutablestring{
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 obj
ects
}
}
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".
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.
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.
The java string charAt() method returns a char value at the given index number.
The index number starts from 0. It returns StringIndexOutOfBoundsException if
given index number is greater than this string or negative index number.
public class CharAtExample
{
public static void main(String args[])
{
String name="javatpoint";
char ch=name.charAt(4);
System.out.println(ch);
}
}
Output:
t
It compares strings on the basis of Unicode value of each character in the strings.
if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0
public class CompareToExample
{
public static void main(String args[])
{
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
System.out.println(s1.compareTo(s5));
}
}
Output:
0
-5
-1
2
public class ConcatExample
{
public static void main(String args[])
{
String s1="java string";
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}
}
Output:
java string
java string is immutable so assign it explicitly
The java string contains() method searches the sequence of characters in this
string. It returns true if sequence of char values are found in this string otherwise
returns false.
class ContainsExample
{
public static void main(String args[])
{
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}
}
Output
true
true
false
public class EndsWithExample
{
public static void main(String args[])
{
String s1="java by javatpoint";
System.out.println(s1.endsWith("t"));
System.out.println(s1.endsWith("point"));
}
}
Output:
true
true
The java string equals() method compares the two given strings based on the
content of the string. If any character is not matched, it returns false. If all
characters are matched, it returns true.
public class EqualsExample
{
public static void main(String args[])
{
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}
}
Output:
true
false
false
The String equalsIgnoreCase() method compares the two given strings on the
basis of content of the string irrespective of case of the string. It is like equals()
method but doesn't check case. If any character is not matched, it returns false
otherwise it returns true.
public class EqualsIgnoreCaseExample
{
public static void main(String args[])
{
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
String s4="python";
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s1.equalsIgnoreCase(s4));
}
}
Output
true
true
false
The java string getBytes() method returns the byte array of the string. In other
words, it returns sequence of bytes.
public class StringGetBytesExample
{
public static void main(String args[])
{
String s1="ABCDEFG";
byte[] barr=s1.getBytes();
for(int i=0;i<barr.length;i++)
{
System.out.println(barr[i]);
}
}
}
Output:
65
66
67
68
69
70
71
The java string length() method length of the string. It returns count of total
number of characters. The length of java string is same as the unicode code units of
the string.
public class LengthExample
{
public static void main(String args[])
{
String s1="javatpoint";
String s2="python";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
Output
string length is: 10
string length is: 6
The java string replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.
public class ReplaceExample1\
{
public static void main(String args[])
{
String s1="javatpoint is a very good website";
String replaceString=s1.replace('a','e');
System.out.println(replaceString);
}
}
Output
jevetpoint is e very good website
The java string replaceAll() method returns a string replacing all the sequence of
characters matching regex and replacement string.
public class ReplaceAllExample1
{
public static void main(String args[])
{
String s1="javatpoint is a very good website";
String replaceString=s1.replaceAll("a","e");
System.out.println(replaceString);
}
}
Output
jevetpoint is e very good website
We pass begin index and end index number position in the java substring method
where start index is inclusive and end index is exclusive. In other words, start
index starts from 0 whereas end index starts from 1.
public class SubstringExample
{
public static void main(String args[])
{
String s1="javatpoint";
System.out.println(s1.substring(2,4));
System.out.println(s1.substring(2));
}
}
Output
va
vatpoint
The java string toLowerCase() method returns the string in lowercase letter. In
other words, it converts all characters of the string into lower case letter.
public class StringLowerExample
{
public static void main(String args[])
{
String s1="JAVATPOINT HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}
Output:
javatpoint hello string
The java string toUpperCase() method returns the string in uppercase letter. In
other words, it converts all characters of the string into upper case letter.
Output:
HELLO STRING
The java string trim() method eliminates leading and trailing spaces. The unicode
value of space character is '\u0020'. The trim() method in java string checks this
unicode value before and after the string, if it exists then removes the spaces and
returns the omitted string.
public class StringTrimExample
{
public static void main(String args[])
{
String s1=" hello string ";
System.out.println(s1+"javatpoint");
System.out.println(s1.trim()+"javatpoint");
}
}
Output
hello string javatpoint
hello stringjavatpoint
The java string valueOf() method converts different types of values into string.
By the help of string valueOf() method, you can convert int to string, long to
string, boolean to string, character to string, float to string, double to string, object
to string and char array to string.
public class StringValueOfExample
{
public static void main(String args[])
{
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);
}
}
Output:
3010
Constructor Description
creates an empty string buffer with the initial capacity of
StringBuffer()
16.
StringBuffer(String str) creates a string buffer with the specified string.
StringBuffer(int creates an empty string buffer with the specified capacity
capacity) as length.
Modifier and
Method Description
Type
is used to append the specified string with
public this string. The append() method is
synchronized append(String s) overloaded like append(char),
StringBuffer append(boolean), append(int),
append(float), append(double) etc.
public insert(int offset, String is used to insert the specified string with
synchronized s) this string at the specified position. The
insert() method is overloaded like
insert(int, char), insert(int, boolean),
StringBuffer
insert(int, int), insert(int, float), insert(int,
double) etc.
public replace(int startIndex,
is used to replace the string from specified
synchronized int endIndex, String
startIndex and endIndex.
StringBuffer str)
public
delete(int startIndex, is used to delete the string from specified
synchronized
int endIndex) startIndex and endIndex.
StringBuffer
public
synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() is used to return the current capacity.
ensureCapacity(int is used to ensure the capacity at least
public void
minimumCapacity) equal to the given minimum.
is used to return the character at the
public char charAt(int index)
specified position.
is used to return the length of the string
public int length()
i.e. total number of characters.
substring(int is used to return the substring from the
public String
beginIndex) specified beginIndex.
substring(int
is used to return the substring from the
public String beginIndex, int
specified beginIndex and endIndex.
endIndex)
The append() method concatenates the given argument with this string.
class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
The insert() method inserts the given string with this string at the given position.
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
The replace() method replaces the given string from the specified beginIndex and
endIndex.
class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
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.
class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
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 (oldca
pacity*2)+2
}
}
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.
class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
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 (oldca
pacity*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
}
}
Method Description
is used to append the specified string with this string.
public StringBuilder The append() method is overloaded like
append(String s) append(char), append(boolean), append(int),
append(float), append(double) etc.
is used to insert the specified string with this string at
the specified position. The insert() method is
public StringBuilder
overloaded like insert(int, char), insert(int, boolean),
insert(int offset, String s)
insert(int, int), insert(int, float), insert(int, double)
etc.
public StringBuilder
is used to replace the string from specified startIndex
replace(int startIndex, int
and endIndex.
endIndex, String str)
public StringBuilder
is used to delete the string from specified startIndex
delete(int startIndex, int
and endIndex.
endIndex)
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)
is used to return the character at the specified
public char charAt(int index)
position.
is used to return the length of the string i.e. total
public int length()
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.
The StringBuilder append() method concatenates the given argument with this
string.
class StringBuilderExample
{
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
}
}
The StringBuilder insert() method inserts the given string with this string at the
given position.
class StringBuilderExample2
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.
class StringBuilderExample3
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.
class StringBuilderExample4
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
class StringBuilderExample5
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
class StringBuilderExample6
{
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 (oldca
pacity*2)+2
}
}
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.
class StringBuilderExample7
{
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 (oldca
pacity*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
}
}
There are several differences between String and StringBuffer in Java. They are as
follows:
1. String class is immutable, but StringBuffer class is mutable.
2. String objects can be created using string literal and new operator, but
StringBuffer objects can be created only using new operator.
3. String class uses string constant pool to store string objects, but StringBuffer
class does not use string constant pool.
4. Strings are of fixed length, whereas StringBuffers are of variable length.
5. String is slower than StringBuffer.
6. String consumes more memory when we will concat too many strings, but
StringBuffer consumes less memory when we concat or update strings.
7. Java String class overrides the equal() method of the Object class. So, we can
compare contents of two strings by using equals() method. The StringBuffer class
does not override the equals() method of Object class.
8. String should be used when we do not need to change or modify the content of
string. Whereas, StringBuffer should be used when we need to change or modify
the content of string frequently.
9. String cannot be used in a threaded environment, but StringBuffer can be used in
a multithreaded environment.
There are mainly five differences between StringBuffer and StringBuilder in Java.
They are as follows:
1. Methods of StringBuffer is synchronized. That means, two threads cannot call
methods of StringBuffer simultaneously. Therefore, StringBuffer is thread-safe.
But, methods of StringBuilder is not synchronized. That means, two or more
threads can call methods of StringBuilder simultaneously. Therefore, StringBuilder
is not thread-safe.
2. It is faster than StringBuffer.
3. It is more efficient than StringBuffer.
4. StringBuilder was added in Java 5 version, whereas StringBuffer was added in
Java 1 version.
5. StringBuffer is used in a multithreaded environment, but StringBuilder is used in
the single threaded environment.