开发者

question on the working of instanceof

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.开发者_Python百科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?


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()


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.


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.


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.


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


Long l1 = null; // false by default null is false for instanceof

Long l2 = Long.getLong("23"); //true if "23" is present in systeme property with long value otherwise false

Long l3 = Long.valueOf(23); // true because 23 is instanceof Long

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜