## 0-TestYourJava - Cast without exception

Moderatoren: pmueller, SE - Design and Construction

GS-812
Windoof-User
Beiträge: 30
Registriert: 25. Apr 2015 12:47

### 0-TestYourJava - Cast without exception

Hello,

I want to point out, that most of the code "TestYourJava" Version 2 may work as expected but also may fail.

The given code will fail:
TestYourJava.java
is Object? false
is null? false
is String? true
is Double? false
Whereas if our write

Code: Alles auswählen

Double o = null;
an exception will be thrown:
TestYourJavaV1.java
is Object? false
Bob: ### java.lang.String cannot be cast to java.lang.Double ###
is null? true
is Double? false
So the function

Code: Alles auswählen

private static <T> T cast(Object i)
may work in some cases.

eichberg
Moderator
Beiträge: 448
Registriert: 25. Sep 2007 12:12
Kontaktdaten:

### Re: 0-TestYourJava - Cast without exception

Well, if you change the declared type of the variable o, the example is surely no longer the same. But – more important - the method cast is not the one that is throwing the class cast exception in your example. If you change the method as follows:

Code: Alles auswählen

    private static <T> T cast(Object i) {
System.out.print("cast ");
T t =  (T) i;
System.out.println("successful");
return t;
}
you'll see that the method is always successful. The exception is thrown when the return value is assigned to local variable o. Moreover, to get the code compiling you had to comment out the line

Code: Alles auswählen

System.out.println("is String?\t" +(o instanceof String));
, which is another hint that the change had – type wise – a more significant impact.