I believe this shows as a compile error because failing the relation check is trivial.
If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
So i'm not dealing with an object. "s" is just an instance variable. But then how does one test for the type of primitive they're dealing with?
How can I tell the difference between String x = "2" and int x = 2? They look identical on the command line.
Matt Kaye wrote:How can I tell the difference between String x = "2" and int x = 2? They look identical on the command line.
Ah, I think I see what you're getting at. All command line parameters to programs are passed as Strings -- there's nothing special about the way java.exe / javaw.exe treat the parameters they receive from the OS.
In case of a Java application, the command line parameters are available in the String array (or String... varargs, but you probably haven't covered that yet) that is the only parameter to the public void main method.
There are no new questions, but there may be new answers.
Joined: Sep 26, 2010
I haven't thought about instanceof that much, I use it in equality checks.
Here's a code that illustrates the uses of instanceof.
The output is
Hopefully this example illustrates the good and bad of instanceof.
As you pointed out, the instanceof doesn't compile when string / integer are mixed.
And, we can't write class A extends Integer to test A instanceof Integer because class Integer was declared final.
Also, you may want to look at pages on this site: JavaExamples