String Class
String is a group of Characters. Thus, String class used to represent these group of characters.
String is a Final class i.e. no subclass will be created for this.
It implements interfaces like - Comparable, Serializable and charSequence.
From Comparable interface it implements compareTo() method and implements it.
Objects of String class are immutable, i.e. content inside them cannot be modified.
We can create string with new operator or with double quotes i.e. without new.
Eg.:
String str = new String ("Hello"); //With new
String str1 = "Java"; //Without new
1) Creating object with new operator :-
- A new String Object will be created every-time i.e. we can create multiple objects with same string class.
- JVM will verify that String Literal is present in String Constant Pool or not.
- If not, then it creates new object inside the String Constant Pool.
- If String Literal is available, then ignores that.
- It also creates another new object inside the pool with new operator and assign its address to the String Reference.
String str = new String ("Hello");
String str1 = new String ("Hello");
Here, str =! str1 as they have different addresses.
2) Creating string without new operator :-
- JVM will create an object of string class with content present in double quotes.
- For that, JVM will verify that String Literal is present in String Constant Pool or not.
- If not, then it creates new object inside the String Constant Pool and newly created object address will be assigned to it.
- If String Literal is available in pool, then address of existing object will be assigned to it.
- With this, we can create only one object with same String Class.
String s1 = "Java";
String s2 = "Java";
Here, s1 == s2, as they both points to the same address.
Program to demonstrate String Class concept.
class Strings{
public static
void main(String[] args) {
String s = "JAVA";
String str = new String("Hello");
String str1 = new String("Hello");
String s1 = "JAVA";
if(str==str1)
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");
if(s==s1)
System.out.println("Strings are equal");
else
System.out.println("Strings are not equal");
}
}
Important Points -
- Object created with new operator will create in HEAP memory.
- Object created without new operator will create in String Constant Pool inside the HEAP memory.
- String Constant Pool is used to maintain the objects having common string values.
- String methods can be applied on String Objects.
It will clear the confusion about String concept, about what is actually happening internally.
ReplyDeleteContents presented beautifully.