Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
Sai Praveen Avatar asked Jan 28 '10 11:01

Sai Praveen


People also ask

What type of operator is Instanceof?

instanceof is a binary operator we use to test if an object is of a given type. The result of the operation is either true or false. It's also known as a type comparison operator because it compares the instance with the type. Before casting an unknown object, the instanceof check should always be used.

Does Instanceof work for interfaces?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.

Does Instanceof work for primitives?

Primitive values can't leverage the instanceof operator, which is a bit of a letdown. To make matters worse, JavaScript's built-in objects such as Boolean , String and Number can only be used with instanceof to check for instances created using the corresponding constructor.

Does Instanceof work for subclasses?

As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface. It is also referred to as the comparison operator because of its feature of comparing the type with the instance.


2 Answers

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

like image 128
Michael Borgwardt Avatar answered Oct 07 '22 04:10

Michael Borgwardt


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.

like image 20
dfa Avatar answered Oct 07 '22 03:10

dfa