String class
The string is an object that represents the sequence of characters.For example:
char[] ch={'l','e','a','r','n','j','a','v','a'};
String s=new String(ch);
Equal to
String s="learnjava";
Example
public class Demo{
public static void main(String args[]){
String s1="java"; //creating string by string literal
char ch[]={'s', 't', 'r' ,'i', 'n', 'g', 's'}; // character array
String s2=new String(ch); //converting char array to string
String s3=new String("Hello"); //creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output
java
strings
Hello
When creating a String object using the new() operator, it always creates a new object in heap memory. If we create an object using String literal syntax. It may return an existing object from the String pool if it already exists.
Ways of creating String object.
- By string literal
- By new keyword
String Literal
The String literal is created by using double quotes.
For Example:
String str="hello";
Every 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 pool, a new string instance is created and kept in the pool.
Example
String s1="hello";
String s2="hello"; // s2 will not create new instance.
By new keyword
String str=new String ("hello"); //creates two objects and one reference variable
In this case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "hello" will be placed in the string constant pool.
The variable str will refer to the object in a heap (non-pool).
Use of String literal?
- To use Java more memory efficiently.
Use Cases
String s1="hello";
String s2="hello";
System.out.print(s1.hashCode()==s2.hashCode()); //true
System.out.print(s1==s2); //true
System.out.print(s1.equals(s2)); //true
String s3=new String("hello");
String s4=new String("hello");
System.out.print(s3.hashCode()==s4.hashCode()); //true
System.out.print(s3==s4); //false
System.out.print(s3.equals(s4)); //true