String in Java
String in Java
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:
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 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.
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.
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 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".
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
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).
StringExample.java
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.
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.java
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 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 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
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output:
Sachin Tendulkar
In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.
As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one
object "Sachin". If one reference variable changes the value of the object, it will be affected by all
the reference variables. That is why String objects are immutable in Java.
Java String compare
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
The String class equals() method compares the original content of the string. It compares values
of string for equality. String class provides the following two methods:
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
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
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
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(s2)); //true
}
}
Output:
false
true
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
Teststringcomparison3.java
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
nonpool)
}
}
Output:
true
false
The above code demonstrates the use of == operator used for comparing two String objects.
The String class 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.
Teststringcomparison4.java
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
In Java, String concatenation forms a new String that is the combination of multiple strings. There
are two ways to concatenate strings in Java:
Java String concatenation operator (+) is used to add strings. For Example:
TestStringConcatenation1.java
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s); //Sachin Tendulkar
}
}
Output:
Sachin Tendulkar
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
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s); //80Sachin4040
}
}
Output:
80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
The String concat() method concatenates the specified string to the end of current string. Syntax:
TestStringConcatenation3.java
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
}
}
Output:
Sachin Tendulkar
The above Java program, concatenates two String objects s1 and s2 using concat() method and
stores the result into s3 object.
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.
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).
TestSubstring.java
The above Java programs, demonstrates variants of the substring() method of String class. The
startindex is inclusive and endindex is exclusive.
The java.lang.String class provides a lot of built-in methods that are used to manipulate string in
Java. By the help of these methods, we can perform operations on String objects 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.
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Stringoperation1.java
Output:
SACHIN
sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
Output:
Sachin
Sachin
Java String startsWith() and endsWith() method
The method startsWith() checks whether the String starts with the letters passed as arguments and
endsWith() method checks whether the String ends with the letters passed as arguments.
Stringoperation3.java
Output:
true
true
Java String charAt() Method
Stringoperation4.java
Output:
S
h
Java String length() Method
The String class length() method returns length of the specified String.
Stringoperation5.java
Output:
6
Java String valueOf() Method
The String class valueOf() method coverts given type such as int, long, float, double, boolean, char
and char array into String.
Stringoperation7.java
1010
Java String replace() Method
The String class replace() method replaces all occurrence of first sequence of character with second
sequence of character.
Stringoperation8.java
Output:
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.
Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.
The append() method concatenates the given argument with this String.
StringBufferExample.java
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
}
}
Output:
Hello Java
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
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
}
}
Output:
HJavaello
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.replace(1,3,”Java”);
System.out.println(sb); //prints HJavalo
}
}
Output:
HJavalo
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to
endIndex.
StringBufferExample4.java
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.reverse();
System.out.println(sb); //prints olleH
}
}
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
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 (oldcapacity*2)+2
}
}
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
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 (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
}
}
Output:
16
16
34
34
70
Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:
2) String is slow and consumes more StringBuffer is fast and consumes less
memory when we concatenate too many memory when we concatenate t strings.
strings because every time it creates new
instance.
3) String class overrides the equals() StringBuffer class doesn't override the
method of Object class. So you can equals() method of Object class.
compare the contents of two strings by
equals() method.
4) String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory
Java toString() Method
If you want to represent any object as a string, toString() method comes into existence.
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.
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.
Student.java
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
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
class Student{
int rollno;
String name;
String city;
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.