+ 1

Does anyone knows why this code does not work correctly?

https://code.sololearn.com/cG4i5perX4Im/?ref=app

24th Jan 2019, 1:05 PM
Mohamad Pishdad
Mohamad Pishdad - avatar
6 Respostas
+ 3
You have to know that all literal strings (like "teletext") are cached in a pool of objects and used when you require them.. This make java create few strings objects when literal string are needed.. Example. String hi= "teletext"; Here java assign to hi a reference to cached String("teletext") so hi and "teletext" are same reference then hi=="teletext" return true. Anyway i suggest to not think about it and use always equals method
24th Jan 2019, 2:18 PM
KrOW
KrOW - avatar
+ 2
You have to: - Declare str like a String object - Compare two strings require use of .equals method because == compare the objects and not the string content - Remove unuseful String cast in last call to println (optional)
24th Jan 2019, 1:50 PM
KrOW
KrOW - avatar
+ 1
KrOW I forgot to declare the String class,, I rewrote the code with the equals method you mentioned and it worked. (thanks) my question is why the first conditional sentence comes out true and the second one comes out false ?? (both of them are String comparisons)
24th Jan 2019, 2:07 PM
Mohamad Pishdad
Mohamad Pishdad - avatar
+ 1
KrOW thanks for the answer,,, I think in the second statement, the String ( "e" ) object doesn't get cached as you said.
24th Jan 2019, 2:22 PM
Mohamad Pishdad
Mohamad Pishdad - avatar
+ 1
Though an "e" cached string will be created from VM it will not used in comparison (eg. s will be created ex-novo). See here for understand better the concept of cached strings pool https://www.journaldev.com/797/what-is-java-string-pool
24th Jan 2019, 2:41 PM
KrOW
KrOW - avatar
0
It is supposed to print "e found" three times ,, but it doesn't.
24th Jan 2019, 1:07 PM
Mohamad Pishdad
Mohamad Pishdad - avatar