Describe the effect of the following Java statements String
Describe the effect of the following Java statements
String sentence; //line 1
sentence = new String(\"Java Programming\"); //line 2
sentence = \"Java Programming\"; //line 3
Solution
Answer:
In first line declared a String object that sentence.
in second line, we alllocated a memory and assigned some value by using new operator to that object. Since we used new operator to initializing the sentence object, it will treat like String object.
in third line we assigned a value directly with out any new operator. so we will call it like String literals.
String objects are stored in heap memory
String literals are stored in String pool memory in Heap memory.
If we assign same value to another String literal then same value reference will be given both the objects thats why we apply == operatr on these two objects it will return true
If we assign same value to another String object by new operator then different memory reference will be given to each object thats why if you apply == operator on both objects it will return false.
in this case, we have to use equals() method to compare both objects.
