Java 16 Tutorial
Java Other Versions Tutorials
Java 16 Useful Resources
Selected Reading
- Java 16 - Deprecation & Removals
- Java 16 - Other Changes
- Java 16 - Garbage Collectors
- Java 16 - Packaging Tools
- Java 16 - Record
- Java 16 - Warnings for Value-Based Classes
- Java 16 - Pattern Matching for instanceof
- Java 16 - Sealed Classes
- Java 16 - Environment Setup
- Java 16 - Overview
- Java 16 - Home
Java Other Versions Tutorials
- Java 15 Tutorial
- Java 14 Tutorial
- Java 13 Tutorial
- Java 12 Tutorial
- Java 11 Tutorial
- Java 10 Tutorial
- Java 9 Tutorial
- Java 8 Tutorial
- Java Tutorial
Java 16 Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Java 16 - Pattern Matching for instanceof
Java 16 - Pattern Matching for instanceof
Java 14 introduces instanceof operator to have type test pattern as is a preview feature. Type test pattern has a predicate to specify a type with a single binding variable. It continues to be a preview feature in Java 15 as well. With Java 16, this feature is now a part of standard depvery.
Syntax
if (person instanceof Employee e) { return e.getEmployeeId(); }
Example
Consider the following example:
ApiTester.java
pubpc class APITester { pubpc static void main(String[] args) { Person manager = new Manager(23, "Robert"); manager.name = "Robert"; System.out.println(getId(manager)); } pubpc static int getId(Person person) { if (person instanceof Employee e) { return e.getEmployeeId(); } else if (person instanceof Manager m) { return m.getManagerId(); } return -1; } } abstract class Person { String name; String getName() { return name; } } final class Employee extends Person { String name; int id; Employee(int id, String name){ this.id = id; this.name = name; } int getEmployeeId() { return id; } } final class Manager extends Person { int id; Manager(int id, String name){ this.id = id; this.name = name; } int getManagerId() { return id; } }
Compile and Run the program
$javac APITester.java $java APITester
Output
23Advertisements