Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6
Nasratullah Talash In example #1 <text1> and <text2> are string literals, literals are cached to optimize memory usage. When a string literal is created, system checks the cache for such a literal having similar content. Any string literal with similar content will be set to refer to the same object that had already been created in cache, this prevents multiple allocations for similar string, and saves memory. The relationship operator == compares references, that is why `text1 == text2` evaluates to true (in example #1), they both point to the same string object in cache. In the second example, the `new` operator returns a new string object, this new string is created disregarding whether there's already such a string in cache. NOTE: * equals() method compares content. * == operator compares references. * String literals are string object too, it's just they can be cached. P.S. Please add Java in Relevant Tags Hth, cmiiw
23rd May 2019, 8:38 AM
Ipang
23rd May 2019, 8:23 AM
Danijel Ivanović
Danijel Ivanović - avatar
+ 15
https://code.sololearn.com/cNRji1rx4NY2/?ref=app https://code.sololearn.com/c3pjhOamCg9L/?ref=app
23rd May 2019, 11:46 AM
MeanMachine
MeanMachine - avatar
+ 13
Comparing Objects Remember that when you create objects, the variables store references to the objects. So, when you compare objects using the equality testing operator (==), it actually compares the references and not the object values. https://www.sololearn.com/learn/Java/2178/
24th May 2019, 1:49 PM
MeanMachine
MeanMachine - avatar
+ 5
Both will return true - assuming you use `equals` method for comparison in example #1 and example #2. If you use == operator to compare then you will get different results.
23rd May 2019, 7:50 AM
Ipang