JAVA -Consider this program:
public class Main {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";
String s3 = "hello";
System.out.println(s1 == s3);
System.out.println(s1.equals(s3));
System.out.println(s2 == s3);
}
}
When we run the program, the output is:
false
true
true
Explain why this is the output, using words and/or
pictures.
Answer: Hey!! Kindly finds your solution below. Let me know if any issue.Thanks.
String s1 = new String (“hello”);
This statement creates a string object in the Heap memory , s1 is reference variable that point this memory location.
String s2 = “hello”;
This statement creates String literal in the String Pool.
So, after seen above statements, we understand that s1 points Heap memory location and s2 points to String pool’s Location. S1 and s2 are reference variable to access memory locations.
When we compare both reference variables if they are equal:
If (s1==s2) this statement return false.(locations are different.
Whereas s2.equals (s1) it returns true because it checks individual characters in both reference variables.
s3 =”hello”; s3 points String Pool’s Location
When we compare both s3 and s2 point String Pool’s Location
If(s2==s3) it returns true.
Get Answers For Free
Most questions answered within 1 hours.