Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If your code has "key = null;" right before the test of instanceof, then the Exception will necessarily be thrown. </p> <p>The reason being that the instancof operator checks the reference of the type of object being pointed to and not how it is declared to be.</p> <p>You can try with this simple example and remove the comments accordingly to see the difference:</p> <pre><code>public static void main(String[] args) { //Object obj = new Integer(9); Object obj = null; if (!(obj instanceof Integer)) System.out.println("Not Integer."); else System.out.println("Is Integer"); } </code></pre> <p>Also, you can find out more details here:</p> <p><a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html" rel="nofollow">http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html</a></p> <p>Hope it helps :)</p> <hr> <p>Full blown example of Java Generics:</p> <pre><code>class GenTest&lt;Key extends Integer, Value&gt;{ Key key; Value val; GenTest(Key key, Value val){ this.key = key; this.val = val; System.out.println("Key: " + key + " Value: " + val); } } public class GenericRecap { public static void main(String[] args) { //Object obj = new Integer(9); Object obj = null; if (!(obj instanceof Integer)) System.out.println("Not Integer."); else System.out.println("Is Integer"); new GenTest&lt;Integer, String&gt;(9, "nine"); //new GenTest&lt;String, String&gt;("funny", "nine"); // In-Error } } </code></pre> <p>Also note that by having 'Key extends Integer', an exception will be thrown during Runtime if you pass that does not subclass Integer. Furthermore, if you're using and IDE that checks for it, it'll be flag as 'Type not within bound' of the GenTest Class.</p> <p>Floats and Integer all inherit from Number. Thus you can 'extend Number' and then check for 'instanceof Integer' or 'instanceof Float' depending on how you want to use it in your code.</p> <p>Hope it helps :) Cheers!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload