Java null type casting
So we use null mostly for JVM that this object can be garbage collected now? If you assign null or anything else, for that matter to a variable or field, then the object that was previously referred to by that variable or field may become eligible for garbage collection. Add a comment. Active Oldest Votes. Mightian Mightian 6, 3 3 gold badges 39 39 silver badges 50 50 bronze badges.
The Overflow Blog. Stack Gives Back Safety in numbers: crowdsourcing data on nefarious IP addresses. Featured on Meta. New post summary designs on greatest hits now, everywhere else eventually. Linked Related Hot Network Questions. Just an intersting side-note on this topic. I had this code: v. This confused the heck out of me as I was sure you can cast a null.
Of course, I was right, you CAN cast a null, you just cannot asign it to a simple type! Mike Simmons. I'm not sure what you mean by a "simple type". A primitive type perhaps? The following will also throw a NullPointerException if value is null: v. Casting to a primitive will throw an NPE if the reference is null.
Darryl Burke. The previous code will also throw a NPE if v. This is probably a result of auto-unboxing invoking Double doubleValue on the null reference, but it doesn't show up in the stack trace. I think you're probably responding to the previous version of my post, in which I misunderstood part of what Etienne said. I've corrected that. Sorry about the mix up. The case of v. In that case, as Etienne said, the cast wouldn't throw an NPE, but the assignment would.
My own post was about an alternate scenario in which the cast causes the NPE, not the assignment. John McSmith. Let's assume that we have a BasicDBObject named result. This JSON document may or may not contain the key name.
If the document doesn't contain the key, result. The first snippet runs on any type returned by result. So it makes only sense to compare the snippets if result. I assume so. The type cast is a noOp in byte code. So the real difference is that the first snippet calls name. The result is the same but the method call may be slower than the direct access to name. If the first is really slower depends on the optimizing that will be done by the compiler and runtime environment.
You should benchmark it with the version of java currently in use, if you are interested in the result.
Sign up to join this community. The best answers are voted up and rise to the top. Stack Overflow for Teams — Collaborate and share knowledge with a private group.
0コメント