[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 552
  • Last Modified:

insanceof question

Why can't I get this to compile?

public class InstanceofTest {
    public static void main(String args[]){
        Double a = new Double(0.0d);
        if(a instanceof Integer){
            System.out.println("true");
        }
        else{
            System.out.println("false");
        }
    }
 }

here's what I get:
F:\>javac InstanceofTest.java
InstanceofTest.java:4: inconvertible types
found   : java.lang.Double
required: java.lang.Integer
        if(a instanceof Integer){
           ^
1 error


this kind of error doesn't make any sense to me being I thought instanceof was precisely to compare objects and simply return true or false
0
day7
Asked:
day7
  • 3
  • 2
  • 2
  • +1
2 Solutions
 
objectsCommented:
Error is because a could not possibly be an Integer

To make it compile try changing the declaration to

  Number a = new Double(0.0d);
0
 
CEHJCommented:
Would compile with

Object a = new Double(0.0d);
0
 
day7Author Commented:
ok, but doesn't that defeat the purpose of instanceof?  why does it matter that a couldn't be an Integer? why doesn't it just return false?
What are the rules, then? so I know how to use it correctly...I haven't seen that explained in any of the tutorials, etc. on instanceof
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
objectsCommented:
The var must be an instance of a superclass of the class being tested against.
0
 
CEHJCommented:
>> ok, but doesn't that defeat the purpose of instanceof?

Not really. instanceof is for runtime checking not compile time.
0
 
day7Author Commented:
ok, I think I got the idea,
thanks
0
 
aozarovCommented:
>> What are the rules, then?
The compiler tries to catch as many errors as possible during compilcation time.
As said before, Becuase Double apparent type can never hold an Integer instance (due to java single inheritence), the compiler
can tell that and will ommit an error (as this line does not make any sense, if you want it to fail all the time then do if (false) instead).
If Double was an interface or a parent of Integer then the compiler will pass it as it can't tell if its wrong during compilation time.
0
 
CEHJCommented:
:-)
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now