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)
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)
Every object descends from 'Object'. Your statement will always be true.
Everything extends Object, so you will always get true here (unless obj is null).
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.
Is this a trick question?
Object obj = new Object() {{ System.out.println(false); System.exit(0); }};
System.out.println(obj instanceof Object);
The only way to make it false is not to give it an object, give it a null reference
Discussed here
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 a type parameter and a local class, at different points within the same method:
public class MySillyClass<Object> {
public static void main(String[] args) {
new MySillyClass<Integer>().doWeirdStuff();
}
public void doWeirdStuff() {
Object value = (Object) "42"; class Object<E> {}
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.
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...