Question about instance operation

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 what result was back. I expected at least for the 2nd and 3rd siso. Can someone explain how the instance works?

+4
source share
5 answers

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

+14
source

l1 instanceof Long

since l1 null , instanceof gives false (as indicated by the Java languange specs)

l2 instanceof Long

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

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

+11
source

Long.getLong(..) returns the long value of the 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 zeros
  • 3 - java.lang.Long (you can check by l3.getClass() ), so true is expected

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

+6
source

I think you can rewrite sop 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 instanceof anything.

+1
source

the instance will check the type of object being checked.

In you, the first two will have a null value, for which it returns false. and the third has a Long object that returns true.

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

0
source

Source: https://habr.com/ru/post/1299641/


All Articles