No Exception While Type Casting with a Null in Java

No Exception while type casting with a null in java

You can cast null to any reference type without getting any exception.

The println method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null". Otherwise it will call the toString method of that object.

Adding more details: Internally print methods call String.valueOf(object) method on the input object. And in valueOf method, this check helps to avoid null pointer exception:

return (obj == null) ? "null" : obj.toString();

For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.

Why does Java compiler allow casting null to primitive type in ternary operator

By Java Language Specification - Conditional Operator, Java will evaluate the conditional expression at run-time, not compile-time. That's why the error is not detected during compile-time:

At run time, the first operand expression of the conditional expression is evaluated first. The resulting boolean value is then used to choose either the second or the third operand expression.

So in your case:

int someMethod() {
return (true ? null : 0);
}

imaging true is a method containing complicated logic, and it makes sense if Java evaluate the 1st operand (in this case is true) at run-time. Then, based on the rule:

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

Since 3rd operand 0 is primitive type (T), the type of the expression would be T type (int). So, unboxing a null reference to int will result in NPE.

how can null be casted to Throwable super((Throwable)null);

How can null be casted to (Throwable)? null is not a class right?

null doesn't have a type.
null can be cast to any class or interface type. It can't be cast to a primtive.

Throwable is a class in the package of java.lang.

You can't cast classes, only references.

String s = "Hello";

Here the variable s is a reference not a class or an object, nor even a String.

Throwable t = new Throwable();

Here the variable t is a reference to a Throwable but it can be set to null;

Throwable t = null; // the reference doesn't point to any object.


Related Topics



Leave a reply



Submit