In: Computer Science
Consider this program: public class Main { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); System.out.println(s1 == s2); System.out.println(s2 == s3); System.out.println(s2.equals(s3)); } } When we run the program, the output is: true false true Explain why this is the output, using words and/or pictures.
Answer:
Given Code:
/*class definition*/
public class Main
{
/*class definition*/
public static void main(String[] args)
{
/*variables initialization*/
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
/*print below comparisions*/
System.out.println(s1 == s2);
System.out.println(s2 == s3);
System.out.println(s2.equals(s3));
}
}
Output:
true
false
true
The above output is generated why because in the program s1,s2 and s3 are three strings that holds the same string "hello". But here problem is we are comparing in two ways one is == operator and another one is equals() method. When we comparing using == operator it comares the refernce or address of the objects. if the two objects refer same address location then it prints true and when coming to equals() method it compares the contents in the objects that means in the program the content is hello in objects.
so
s1 and s2 refer same address so it prints true. (using == operator)
s2 and s3 doesn't refer same address so it is false. (using == operator)
s2 and s3 objects having same content "hello" so it prints true (using equals() method)
String s1="hello"
String s2="hello"
The above two are in same location
String s3=new String("hello")
it creates a new address space for s3 so s3 address is different from s2 but contents are same.
Source Code:
Output:
Code to Copy is pasted above. See images of code for
indentation.