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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With