String in Java
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.
1. By string literal
2. By new keyword
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 object or instance is returned. If string doesn't exist in the
pool, a new string object or instance is created and placed in the String constant pool.
For example:
String s1="Welcome";
1
In the given 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.
To make Java more memory efficient (because no new objects are created if it exists already in string
constant pool).
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).
Example:
System.out.println(s1);
}}
2
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.
class Demo{
String s="Sachin";
o/p: 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.
3
As you can see in the given 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:
class Demo{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
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.
1. char charAt(int index) – return the character value at the given index number.
The index number starts from 0 and goes to n-1, where n is length of the string. It
returns StringIndexOutOfBoundsException if given index number is greater than or equal
to this string length or a negative number.
Eg:
class Demo{
String str="Ram";
System.out.println(str.charAt(0)); // R }}
4
2. int length() – returns the total number of character in the string.
Eg:
class Demo{
System.out.println(str.length()); // 9
3. String concat(String str) – combines specified string at the end of this string. It returns
combined string. It is like appending another string.
Eg:
class Demo{
String str="Manjeet";
System.out.println(""+str.concat(" Kumar"));}
4. boolean equals(String str) – return true if this String contains the same character as str(including
case) and false otherwise.
Eg:
class Demo{
String str="Manjeet";
System.out.println(""+str.equals("Manjeet"));
}} output: true
5
5. int compareTo(String str) – return an integer indication if this string is lexically before( a
negative return value), equal to(a zero return value) or lexically after( a positive return value).
class Demo{
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));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}
6. String replace(char oldchar, char newchar) – return a new String that is identical with this
String except that every occurrence of old-char is replaced by new-char.
class Demo{
String str="Manjeet";
7. String toLowerCase() – return a new string identical to this string. All uppercase letters are
converted to their lowercase equivalent.
class Demo{
String str="MANJEET";
System.out.println(""+str.toLowerCase());}
o/p: manjeet
6
8. String toUpperCase() – return a new string identical to this string. All lowercase letters are
converted to their uppercase equivalent.
class Demo{
String str="manjeet";
System.out.println(""+str.toUpperCase());
o/p: MANJEET
9. substring
A part of string is called substring. There are two signature of substring() method in Java.
This method returns new String object containing the substring of the
given string from specified startIndex.
class Demo{
String str="manjeet";
System.out.println(""+str.substring(3));
o/p: jeet
This method returns new String object containing the substring of the
given string from specified startIndex to endIndex – 1.
class Demo{
String str="manjeet";
7
System.out.println(""+str.substring(3,6));
o/p: jee
10. String trim() – This method omitted/eliminates leading and trailing space of the given string.
11. split()
The split() method splits the string against given regular expression and returns a array of String.
Parameter
limit: limit for the number of strings in array. If it is zero, it will returns all the
Strings matching in regex.
1 .Eg: split the string on the basis of single while space character ( \\s) or for multiple
while space (\\s+)
class Demo{
String s[]=str.split("\\s");
int i;
for( i=0;i<s.length;i++ )
System.out.println(""+s[i]);
8
Output:
am
5th
semester
B.Tech
student
class Demo{
String str="10/01/2020";
String s[]=str.split("/");
int i;
for( i=0;i<s.length;i++ )
System.out.println(""+s[i]);
Output:
10
01
2020
3.Eg: split the string on the basis of “,” and “?” character.( i.e for multiple regex)
class Demo{
9
String s[]=str.split("[\\,\\?]");
int i;
for( i=0;i<s.length;i++ )
System.out.println(""+s[i]);
Output:
java . string
split method
by Manjeet kumar
4. eg
class Demo{
String str="10/01/2020";
String s[]=str.split("/", 1 );
int i;
for( i=0;i<s.length;i++ )
System.out.println(""+s[i]);
Output:
10/01/2020
5.eg
class Demo{
String str="10/01/2020";
10
String s[]=str.split("/", 2 );
int i;
for( i=0;i<s.length;i++ )
System.out.println(""+s[i]);
Output:
10
01/2020
6.eg
class Demo{
String str="10/01/2020";
int i;
for( i=0;i<s.length;i++ )
System.out.println(""+s[i]);
Output:
10
01
2020
11
12. public char[] toCharArray()
this method converts the String into character array, its length is similar to the string.
Eg:
class Demo{
String str="Manjeet";
char ch[]=str.toCharArray();
int i;
for( i=0;i<ch.length;i++ )
System.out.print(""+ch[i]); }
Output:
Manjeet
import java.io.*;
import java.util.*;
13