String literal and string object ..Is one created on the stack and the other on the heap ?
What is the difference between string literal and string object ?
We know that objects are created on the heap and their referencing variables are on stack
Strings are objects in java so they are created on the heap
String literal is. .. For example string created using " "
String s1="hello"; - this will get a space in intern pool or string literal pool in heap ...which is specific area where only distinct string are stored and incase of duplication only reference is returned to the new string variable
s1.equals(s2); --returns true and checks only contents not address
S1==S2 ;--also returns true which actually checks the address these variables are referring to ...so they are pointing to the same address
Now ,string objects
string s =new string("hello");
Now s.equals(s1); //True as the contents of the string is Same i.e. "hello"
s==s1;// False because although they are same strings we used new keyword to create s string so its not created in the string pool ..the string variable s is allotted a new address as it asked for a new address using the NEW keyword in the heap like any other object
Now this string is not stored in the intern pool or string literal pool ..
It is created somewhere else in the heap ..
Conclusion- string literal is preffered when we know the value of string in compile time where's we create string using new keyword when we want to create string in runtime. Although both are created in the heap, one is created in the string pool and other like another other object.
So what the JVM does is its scans for string literals in the .class file after javac compilation of your source code of .java file and it then checks for if reference is already there in the intern pool.. if not it creates a reference and if anywhere in the code there same string is used it assigns the same reference or if a reference to that string already exists in the internal pool then it assigns that same reference.