Hello.. I was doing a code review and found out that they have typecasted a null object. I was under the impression that it will throw a null pointer exception.But it didnt. Wht is the use of doing this? This is the code public void methodName(UserDefinedObject obj) { ....... } They have used the following code to invoke methodName methodName((UserDefinedObject) null); A null can be passed directly instead of type casting. Does this have any performance issues? I also saw another style of coding. I normally use the following if(abc!=null). But I came across the following style if(null!=abc). Again any specific reason for doing this this or is it only a coding style?
Hi. There's no need to do the typecasting if you're passing a null, since a null is valid for any object (in a sense). The compiler will give you the same bytecode in both ways, though, since this is cought at compile-time and not at runtime (the null is explicit). So - no performance issues here. Regarding the second question - it doesn't matter. It's only a coding style (I'd say - not a very nice style, but I never argue about coding or coffee). Nimo.
The reason for the typecast may be that methodName() is overloaded. If you pass null to an overloaded method, the compiler may not be able to decide which version you want and so won't compile the code. The cast tells the compiler which overload to invoke.
I, too, had the similar impression that a NullPpointerException will most definitely be thrown, but it wasn't. Then in Java forum, I was pointed to the fact that the JLS specify so.
Originally posted by Vinu krish: I also saw another style of coding. I normally use the following if(abc!=null). But I came across the following style if(null!=abc). Again any specific reason for doing this this or is it only a coding style?
I see no reason to do this. I have seen something similar with Strings that is a good idea. Instead of doing this: if (myString.equals("ABC")) do this: if ("ABC".equals(myString)) The first can cause a NullPointerException. The second can't.