views:

135

answers:

5
Long l1 = null;
Long l2 = Long.getLong("23");
Long l3 = Long.valueOf(23);

System.out.println(l1 instanceof Long);  // returns false
System.out.println(l2 instanceof Long);  // returns false
System.out.println(l3 instanceof Long);  // returns true

I could not understand the output returned. I was expecting true atleast for 2nd and 3rd syso's. Can someone explain how instanceof works?

+9  A: 

l1 instanceof Long

since l1 is null, instanceof yields false (as specified by the Java languange specs)

l2 instanceof Long

this yields false since you are using the wrong method getLong:

Determines the long value of the system property with the specified name.

dfa
see http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Long.html#getLong%28java.lang.String%29
Jean-Philippe Caruana
ah, the ugly oracle favicon is now on the javadocs. Blast.
Bozho
+12  A: 

This has nothing to do with instanceof. The method Long.getLong() does not parse the string, it returns the contents of a system property with that name, interpreted as long. Since there is no system property with the name 23, it returns null. You want Long.parseLong()

Michael Borgwardt
(added a missing apostrophe)
Bozho
@Bozho: thanks :)
Michael Borgwardt
+5  A: 

Long.getLong(..) returns the long value of a system property. It returns null in your case, because there is no system property named "23". So:

  • 1 and 2 are null, and instanceof returns false when comparing nulls
  • 3 is java.lang.Long (you can check by outputting l3.getClass()) so true is expected

Instead of using Long.getLong(..), use Long.parseLong(..) to parse a String.

Bozho
+1. nice answer
dfa
A: 

the instance of will check the type of the object under inspection.

In you the first two will have null value for which it returns false. and the 3rd one has the Long object which return true.

You can get more info on instaceof at this java glossary site: http://mindprod.com/jgloss/instanceof.html

GK
A: 

I guess one can rewrite the sop's as :

System.out.println(l1 != null && l1 instanceof Long);
System.out.println(l2 != null && l2 instanceof Long);
System.out.println(l3 != null && l3 instanceof Long);

As always null cannot be an instanceof anything.

fastcodejava