Consider
Object obj = ....;
System.out.println(obj instanceof Object);
What should obj be so that the answer is false (Any other option other than null)
Is this a trick question?
Object obj = new Object() {{ System.out.println(false); System.exit(0); }};
System.out.println(obj instanceof Object);
This will print false:
public final class Foo {
static private final class Object {
}
static public void main(String[] args)
{
java.lang.Object o = new java.lang.Object();
System.out.println(o instanceof Object);
}
}
It's not quite what you asked for, but the best I could think of...
None AFAIK. Did you get this as an interview question?
By definition, it should return true if you can cast the variable into an Object, and all non-nulls should be convertible. Perhaps there is some trick with generics, but I doubt that.
Obviously if Object refers to java.lang.Object (as defined by the boot classloader) this is not possible as every class in the process must descend from java.lang.Object
However you can define something else called Object in an inner scope, hiding java.lang.Object.
Here's an example where the name Object refers to java.lang.Object at the start of a method and a local class later:
public static void main(String[] args) {
Object value = "42"; class Object {}
System.out.println(value instanceof Object);
}
This is a slight cheat because the declaration of value is not a single statement but a statement followed by a local class definition.
I tested this in Eclipse 3.5.0, but I wouldn't be surprised if other compilers behave differently with a pathological example like this.
public static void main(String[] args) { Object v = (Object)"42"; class Object {} System.out.println(v instanceof Object); }
Feb 12, 2011 at 19:53
Old, old question but:
It could also be an instance of a primitive object like int, double, boolean, etc. If do so, it'll probably return false as well