This post will give you knowledge about the String Class.
In order to master java, you have to master the String Class. The string is a very important class in java. it has so many behaviors. In the few lines, we will see what is the difference between String literal and String objects.
Memory Structure |
When we create an object by using new() operator in java. it will be stored in heap memory.
String str = new String("Hello");
But when you create an object using String literal it will be created in the String pool which is inside the Heap memory.
Memory Referencing |
String str1 = new String("hello");
String str2 = "hello";
String str3 = "hello";
String str4 = new String("hello");
Here, variables str1 and str2 both are String literal objects and str3, and str4 both are String objects.
str1 and str2 both are referring to one memory location and str3 and str4 both are referring to different memory locations.
== vs equals() method
Result |
String str1 = new String("abc");
String str2 = "abc";
System.out.println(str1.equals(str2));
System.out.println(str1==str2);
String str2 = "abc";
System.out.println(str1.equals(str2));
System.out.println(str1==str2);
Here the result of str1==str2 is false because it compares the memory reference. one is a literal object so it is inside the pool and the other is outside of the pool so both are referring to a different location.
The result of str1.equals(str2) is true because this method compares the contents of both objects.
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments
Please comment here...