Java – 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.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?

Best Solution

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