+ 5

Can any one explain this code in java

Why it outputs false in the first case: public class CompareNames { public static void main(String[] args) { String hello=new String("hello world"); String hi = new String(hello); System.out.print((hello==hi)+" "+(hello.equals(hi))); } } // Answer: false true

9th Jun 2020, 10:25 AM
Sujithra
5 Answers
+ 5
In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two: ... In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects. this might help you! most questions are covered already you just need a search using SEARCH BAR :) https://www.sololearn.com/Discuss/886484/?ref=app
9th Jun 2020, 10:31 AM
minirkk
minirkk - avatar
+ 7
Because of "==" operator is used for reference comparison and .equals() method also for reference comparison in Object class but String class override Object class .equals method for content comparison.
10th Jun 2020, 1:16 AM
Ketul Patel
Ketul Patel - avatar
+ 3
Thank you RKK , especially for the reference
9th Jun 2020, 11:47 AM
Sujithra
+ 2
Sujithra you're welcome! 👍😊
9th Jun 2020, 11:49 AM
minirkk
minirkk - avatar
0
->Main difference between .equals() method and == operator is that one is method and other is operator. ->We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects. Hope this is helpful to u
10th Jun 2020, 4:36 AM
Yelchuri Lakshmi Neeraj
Yelchuri Lakshmi Neeraj  - avatar