3 ms·
>> if (str1 != "yes") Thats some dodgy java code right there. (You should use .equals() )
by andy_boot 13y ago
>> if (str1 != "yes")
Thats some dodgy java code right there. (You should use .equals() )
- chii 13y agoits decompiled code, so you'd have to forgive the bad style.
- namdnay 13y agoA) They're literals B) It's been decompiled c) CHICKEEEEEEN
- RyanZAG 13y agoIt's a shame you'be been downvoted even while being correct - I gave you one upvote at least. Decompile is irrelevant here, the only difference is 'str1' might have been named something different in the original code. This is java code, so "string" != "string" will usually return true always, as you are checking if the objects are equal and not whether the contents are equal. Depending on the JRE this code runs on, it would give different output. [1] [1] http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java http://stackoverflow.com/questions/513832/how-do-i-compare-s...
- svachalek 13y agoI believe String literals are guaranteed to be == in the same source file by the spec, although it's been some years since I could quote chapter and verse for that.
- kbolino 13y agoYou are correct (albeit substituting "class" for "source file" since runtime Java has no concept of source files), although the guarantee is stronger than that. Any two identical literals will refer to the same object, since literals are interned, regardless of what classes "own" them. Chapter and verse: JLS §3.10.5, http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5 http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#...
- chimeracoder 13y agoCaveat: This will yield different results whether you initialize the string as > String a = "foo"; vs. > String a = new String("foo");
- fyi80 13y agoParent wrote: "Any two identical literals" The second 'a' is not a literal.
- RyanZAG 13y agoThe OP is still correct though - don't use == for strings, always use .equals() The problem with using == is maintainability and silent failure. Someone may change the program to accept the string from the command line, or just about anything else. As soon as this happens, a string can come in from elsewhere and still have the value "yes" but would still pass the inequality. This bug would be completely silent and incredibly difficult to debug, possibly only arising in strange and unusual circumstances. The only way to really avoid this is to just use .equals() always. Using == for strings in Java is plain terrible coding, and the OP is therefore correct.
- deleted 13y ago[deleted]