Do you really know the instanceof in Java? __java

Source: Internet
Author: User

Instanceof is a simple two-dollar operator that is used to determine whether an object is an instance of a class

Boolean B1 = "Sting" instanceof Object;
B1 is true because string is a subclass of object

Boolean b2 = new string () instanceof string;
B2 is true

Boolean b3 = new Object () instanceof String;
B3 to false object is a parent class

Boolean b4 = ' A ' instanceof Character;
compilation does not pass ' A ' is considered a basic data type here char,instanceof operator can only be used as an object's judgment

Boolean b5 = null instanceof String;
B5 to false this is a instanceof-specific rule: if the left-hand operand is null, the result is returned directly to false, no longer the class of the right-hand operand.

Boolean b6 = (string) null instanceof String;
B6 to false even if the type conversion is still a null

Boolean B7 = new Date () instanceof String;
compilation does not pass the left and right operands of the instanceof operator must have an inheritance or implementation relationship, or else compilation error

Boolean B8 = new Genericclass<string> (). Isdateinstance ("");
Class genericclass<t>{
public boolean isdateinstance (T-t) {
return T instanceof Date;
}

compilation passed , B8 to false because of generics, so the time of bytecode is the object type, where T instanceof date is equivalent to object instance of date.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.