{"id":4630,"date":"2019-10-21T00:55:50","date_gmt":"2019-10-20T15:55:50","guid":{"rendered":"https:\/\/chat-messenger.com\/?p=4630"},"modified":"2023-11-13T01:14:20","modified_gmt":"2023-11-12T16:14:20","slug":"java-instanceof","status":"publish","type":"post","link":"https:\/\/chat-messenger.com\/en\/blog\/java\/java-instanceof","title":{"rendered":"Checking Java variable types with instanceof"},"content":{"rendered":"<h2>Checking the type of a variable<\/h2>\n\n\n\n<p>Here is a sample program for checking variable types in Java.<\/p>\n\n\n\n<p>Since Java is a statically typed language that declares types explicitly, there is no opportunity to check types to that extent. However, when using inherited objects, type checking may be necessary.<\/p>\n\n\n\n<p>How to check types in Java <strong>instanceof<\/strong> Using operators, you can evaluate classes and interfaces with if statements, etc. as shown below.<\/p>\n\n\n\n<div class=\"wp-block-group is-style-big_icon_good\"><div class=\"wp-block-group__inner-container\">\n<p><em>variable<\/em> instanceof class<\/p>\n\n\n\n<p><em>variable<\/em> instanceof interface<\/p>\n<\/div><\/div>\n\n\n\n<p><strong>instanceof<\/strong> A class name or interface name can be specified on the right side of .<strong>instanceof<\/strong> The return value is a boolean; if true, the variable is the specified class or interface.<\/p>\n\n\n\n<div class=\"recommend\">\n<p><a href=\"javascript:clickAdd()\">Chat&amp;Messenger<\/a> is groupware that integrates business chat, web conferencing, file sharing, schedule management, document management, conference room reservation, and attendance management in an easy-to-use manner. Perfect security for businesses,<mark>Available for free!<\/mark><\/p>\n<a href=\"javascript:clickAdd()\"><img style=\"margin:10px;box-shadow: var(--swl-box_shadow);\" src=\"\/images\/cam-top-banner.png\" width=\"700\"><\/a>\n<\/div>\n\n\n\n<h2>sample program<\/h2>\n\n\n\n<p>First, the simplest pattern. Returns true if variable i is Integer, false otherwise.<\/p>\n\n\n\n<h4>sample code<\/h4>\n\n\n\n<div class=\"hcb_wrap\" data-no-translation=\"\"><pre class=\"prism line-numbers lang-java\" data-lang=\"Java\"><code>public static void integerSample() {\n    Integer i = 100;\n    boolean result = i instanceof Integer;\n    System.out.println(result);\n}<\/code><\/pre><\/div>\n\n\n\n<h4>output (result)<\/h4>\n\n\n\n<div class=\"hcb_wrap\" data-no-translation=\"\"><pre class=\"prism line-numbers lang-bash\" data-lang=\"Bash\"><code>true<\/code><\/pre><\/div>\n\n\n\n<p>Since the variable i is an Integer, the result is true. However, this is too obvious to understand what instanceof is for, so we will make it a little more complicated.<\/p>\n\n\n\n<h2>Effective use of instanceof<\/h2>\n\n\n\n<p>One effective use of instanceof is to determine which child class the variable is.<\/p>\n\n\n\n<h4>sample code<\/h4>\n\n\n\n<p>In the sample code, we create an animal class Animal, a Dog class that inherits from the animal class, and a Cat class, and after creating an instance, set variables in the play method. <strong>instanceof<\/strong> The console output is branched based on the judgment. <\/p>\n\n\n\n<div class=\"hcb_wrap\" data-no-translation=\"\"><pre class=\"prism line-numbers lang-java\" data-lang=\"Java\"><code>class Animal {} \nclass Dog extends Animal {}\nclass Cat extends Animal {}\n\npublic class Main {\n    public static void main(String[] args) {\n        instanceofSample();\n    }\n    \n    static void instanceofSample() {\n        Animal dog = new Dog();\n        play(dog);\n        Animal cat = new Cat();\n        play(cat);\n    }\n    \n    static void play(Animal animal) {\n        if (animal instanceof Dog) {\n            System.out.println(&quot;\u304a\u6563\u6b69\u3059\u308b&quot;);\n        } else {\n            System.out.println(&quot;\u732b\u3058\u3083\u3089\u3057\u3067\u904a\u3076&quot;);\n        }\n    }\n}<\/code><\/pre><\/div>\n\n\n\n<h4>output (result)<\/h4>\n\n\n\n<div class=\"hcb_wrap\" data-no-translation=\"\"><pre class=\"prism line-numbers lang-bash\" data-lang=\"Bash\"><code>\u304a\u6563\u6b69\u3059\u308b\n\u732b\u3058\u3083\u3089\u3057\u3067\u904a\u3076<\/code><\/pre><\/div>\n\n\n\n<p>The key point is that in the play method, it is not known whether the animal passed as an argument is a dog or a cat.<\/p>\n\n\n\n<p><strong>instanceof<\/strong> Now, you can also check the subclass instances (Dog or Cat) contained within the superclass (Animal), so you can use it like this.<\/p>\n\n\n\n<h2>Check to see if a specific interface is implemented<\/h2>\n\n\n\n<p>You can check whether a specific interface is implemented for the variable targeted by instanceof. For example, you can use it like this.<\/p>\n\n\n\n<h4>sample code<\/h4>\n\n\n\n<p>In the sample code below, classes for Mr. Sato and Mr. Suzuki are created, and the interface Car is implemented assuming that only Mr. Suzuki owns a car. The goShopping() method assumes the process of going shopping, but it implements Car or branches the console output based on instanceof.<\/p>\n\n\n\n<div class=\"hcb_wrap\" data-no-translation=\"\"><pre class=\"prism line-numbers lang-java\" data-lang=\"Java\"><code>interface Car {}\nclass Sato {}\nclass Suzuki implements Car {}\n\npublic class Main {\n    public static void main(String[] args) throws Exception {\n        instanceofSample();\n    }\n    \n    static void instanceofSample() {\n        Sato sato = new Sato();\n        goShopping(sato);\n\n        Suzuki suzuki = new Suzuki();\n        goShopping(suzuki);\n    }\n    \n    static void goShopping(Object human) {\n        if (human instanceof Car) {\n            System.out.println(&quot;\u8eca\u3067\u884c\u304f&quot;);\n        } else {\n            System.out.println(&quot;\u6b69\u3044\u3066\u884c\u304f&quot;);\n        }\n    }\n}<\/code><\/pre><\/div>\n\n\n\n<h4>Output Results:<\/h4>\n\n\n\n<div class=\"hcb_wrap\" data-no-translation=\"\"><pre class=\"prism line-numbers lang-bash\" data-lang=\"Bash\"><code>\u6b69\u3044\u3066\u884c\u304f\n\u8eca\u3067\u884c\u304f<\/code><\/pre><\/div>\n\n\n\n<p>You can see that the process diverges between cases where Car is implemented and cases where it is not.<\/p>","protected":false},"excerpt":{"rendered":"<p>Checking the type of a variable Introducing a sample program to check the type of a variable in Java. Java explicitly declares types [\u2026]<\/p>","protected":false},"author":1,"featured_media":9054,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"swell_btn_cv_data":""},"categories":[19],"tags":[],"_links":{"self":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts\/4630"}],"collection":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/comments?post=4630"}],"version-history":[{"count":6,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts\/4630\/revisions"}],"predecessor-version":[{"id":9049,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/posts\/4630\/revisions\/9049"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/media\/9054"}],"wp:attachment":[{"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/media?parent=4630"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/categories?post=4630"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/chat-messenger.com\/en\/wp-json\/wp\/v2\/tags?post=4630"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}