When is the "obj instanceof Object" false in Java?

Consider

Object obj = ....; System.out.println(obj instanceof Object); 

What should be so that the answer is false (any other parameter other than null )

+4
source share
10 answers

Object extends everything, so you will always be true here (if obj is not null).

+6
source

Is this a trick?

 Object obj = new Object() {{ System.out.println(false); System.exit(0); }}; System.out.println(obj instanceof Object); 
+38
source

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); } } 

This is not exactly what you asked for, but the best I could come up with ...

+11
source

This will never return false if obj not null

+9
source

Each object descends from the "Object". Your statement will always be true.

+1
source

No AFAIK. Did you get this as an interview question?

By definition , it should return true if you can apply the variable to Object, and all nonzero ones must be convertible. There may be a generic trick, but I doubt it.

0
source

The only way to make it false is to not give it an object, give it a null reference

Discussed here

0
source

Obviously, if Object refers to java.lang.Object (as defined by the loader loader), this is not possible, since each class of the process must be omitted from java.lang.Object

However, you can define something else called Object in the inner scope by hiding java.lang.Object .

Here's an example where the name Object refers to java.lang.Object at the beginning of the method and local class later:

 public static void main(String[] args) { Object value = "42"; class Object {} System.out.println(value instanceof Object); } 

This is a small cheat because the value declaration is not a single statement, but an operator followed by a local class definition.

I tested this in Eclipse 3.5.0, but I won’t be surprised if other compilers behave differently with a pathological example like this.

0
source

Old, old question, but:

  • if obj is null
  • if you use jview back in the late 90s and try the option (don't remember the package by heart).
0
source

It can also be an instance of a primitive object such as int, double, boolean, etc. If so, it will probably also return false

0
source

All Articles