+ 1
Does anyone knows why this code does not work correctly?
6 Antworten
+ 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
+ 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)
+ 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)
+ 1
KrOW thanks for the answer,,, I think in the second statement, the String ( "e" ) object doesn't get cached as you said.
+ 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
0
It is supposed to print "e found" three times ,, but it doesn't.