6 ms·
Sure – that's just casting a null type as a string. So I guess if you have a comparison that somehow casts null to a string before comparing, you could run int
by incongruity 9y ago
Sure – that's just casting a null type as a string.
So I guess if you have a comparison that somehow casts null to a string before comparing, you could run into this issue, but that's still bad programming.
I used to own null@myundergrad.edu as an email alias (with my real university, not that generic .edu, of course) and I got all sorts of interesting things... but that was very intentional on my part.
- monsieurbanana 9y agoI don't think anyone ever argued that this wasn't because of bad programming.
- ajuc 9y agoFunnily enough - it's not the null-> String conversion, it's the "+" operator. That was at one point subject of heated debate in my previous job :) See: "null".equals((String)null) //false "null".equals((String)null+"") //true System.out.print((String)null) // throws NPE System.out.println((String)null) // prints "null", I guess because it appends "\n" inside
- incongruity 9y agoRight, but that operator is implicitly casting the null object to a string type – it has to, in a strict sense... some other languages would raise an error (and many would do the same as Java).
- ajuc 9y agoIt doesn't have to. null.toString() throws NPE as it should. I would expect "foo" + null to throw NPE as well. BTW there's another "fun" gotcha, when you interface java code and oracle database which consider empty string and null to be the same thing. Depending on how you handle data from database you end up with null, "", or "null" :)
- Asooka 9y agoString.valueOf(null) returns "null" though, and that is what "foo" + null uses. I can understand why it would be surprising if you thought it used .toString, but it's clearly listed in the standard.
- LukeShu 9y agoSure, but .toString() can be used to change how your class stringifies, so clearly it is being called at some point (perhaps by String.valueOf()). And indeed, public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java#l2969 http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/s...
- incongruity 9y agoInteresting – I haven't touched Java in years so I'm definitely out of my element with that language, so thank you.
- amenghra 9y agoSystem.out.print((String)null) Does not throw NPE.
- ajuc 9y agoit does here: http://www.javarepl.com/term.html http://www.javarepl.com/term.html But you're right, in regular java environment it doesn't now that I've checked.