• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Pattern Matching Subtypes

 
Greenhorn
Posts: 4
  • Number of slices to send:
    Optional 'thank-you' note:

Hi there!

I am preparing for the java 17 exam and and studying the ocp 17 book. The page 108 says pattern matching must be a subtype and cannot be the same type but I wrote this piece of code in eclipse and it seems to work just fine

Integer x = 123;
if(x instanceof Integer data) { It works ! now I am confuse about it because the book states that it doesn't
}

What am I missing here?
 
Master Rancher
Posts: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:
It sounds like the book is simply wrong on page 108.  Or maybe it was misunderstood?  What exactly does the book say there?
 
Fabio Yasuo Yamashita
Greenhorn
Posts: 4
  • Number of slices to send:
    Optional 'thank-you' note:
Baiscally the book says the pattern variable must be a subtype of the variable on the left side of the expression. It cannot be same.

Integer value = 123;

if(value instanceof Integer) {} compiles
if(value instanceof Integer data) {}  DOES NOT COMPILE. Here is strange because I wrote exactly the piece of code and it compiles.  

 
Marshal
Posts: 28258
95
  • Number of slices to send:
    Optional 'thank-you' note:
It looks to me as if the error message might possibly be referring to the rule that the subtypes used in the switch statement are supposed to cover the type of the switch expression exhaustively. So it would help to know what the error message says.

Also, the pattern matching for switch project was a preview until Java 21, so it's possible that this was one of the features which was modified in that long process. So you should be using the Java 17 compiler to match the exam and not Java 18 and later.

I also didn't see anything in the original JEP which says that the type of the case expression has to be a proper subtype of the type of the switch expression, and that the two couldn't be the same. But perhaps I missed that.
 
Mike Simmons
Master Rancher
Posts: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:

Fabio Yasuo Yamashita wrote:Baiscally the book says the pattern variable must be a subtype of the variable on the left side of the expression. It cannot be same.


Does the book say that the code with Integer does not compile?  Or does it just say that the type of the instanceof needs to be a subtype of the type of the variable?  Does it say that the types can't be the same?  Or did you just infer that from "subtype"?  It would really help to know exactly what the book said.

In an expression like

the type Foo needs to be a subtype of the declared type of x.  But you need to know that "subtype" includes being the same type.  E.g. a Dog is an Animal and a Cat is an Animal, but an Animal is also an Animal.  That's the way "subtype" is defined.
 
Enthuware Software Support
Posts: 4828
52
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
There has been a change in the behavior of instanceof from Java 17 to Java 21. In Java 17, the type expression on the right hand side of the instanceof operator, when it is used for pattern matching (but not when it is used just for type comparison), must be a subtype of the type of the variable given on the left hand side. Java 21 does not impose this restriction.
 
Mike Simmons
Master Rancher
Posts: 4905
74
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
Excellent call out - thank you, Paul A.

Fabio, if you're studying for Java 17, it's probably a good idea to be running JDK 17 when you're testing things.  Usually, it's OK to use a later version.  But in this case, they later allowed something that was initially not allowed.  If you try compiling with JDK 17, you should see the error you expected.

Thinking more though, I think that if the book says something like "the pattern variable must be a subtype of the variable on the left side of the expression" (still haven't seen an actual quote), then it's still wrong here.  Because the pattern variable (right hand side) may actually be totally unrelated to the type of the expression (left hand side).


The compiler will accept this, because it knows that it's theoretically possible for a Foo instance to also implement Serializable.  It would have to be a subclass, and that's not what we have here, obviously.  But if the compiler considers only the type of the expression f, which is Foo, and the type of the pattern s, which is Serializable... considering only those things, and the declarations of Foo and Serializable... it is possible that a Foo could also be Serializable.  So it's allowed.

If you make class Foo final, then it becomes impossible, and is not allowed.  Because Foo itself is not Serializable, and no other subclass of Foo can exist, so no Foo is Serializable, ever.

This is pretty similar to the rules for casting - if a cast is probably impossible based on the types involved, it will not be allowed.  If it's at least theoretically possible based on the type, it's allowed.  It may fail at runtime, but it's allowed.
 
author & internet detective
Posts: 41905
909
  • Number of slices to send:
    Optional 'thank-you' note:
This is the actual text and example from the Java 17 book:

The type of the pattern variable must be a subtype of the variable on the left side of the
expression. It also cannot be the same type. This rule does not exist for traditional instanceof
operator expressions, though. Consider the following two uses of the instanceof operator:

While the second line compiles, the last line does not compile because pattern matching
requires that the pattern variable type Integer be a strict subtype of Integer .

 
Jeanne Boyarsky
author & internet detective
Posts: 41905
909
  • Number of slices to send:
    Optional 'thank-you' note:
Also note that this is in chapter 3 of the book before interfaces  have been covered. So it is covering the basics.

Chapter 7 has a section about instanceof which covers the interface implications.  I believe that is what Mike is referencing in hist post about the section not being complete. It's not because it's split into two!
 
Mike Simmons
Master Rancher
Posts: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:
Thanks for the clarification, Jeanne!
 
Greenhorn
Posts: 8
1
  • Number of slices to send:
    Optional 'thank-you' note:
I discovered the same thing. Only it only compiles in Eclipse and in VSCode (which both use Java 17). However when I run Java from the command line on the same code it does not compile. I'm not sure what is different
 
Jeanne Boyarsky
author & internet detective
Posts: 41905
909
  • Number of slices to send:
    Optional 'thank-you' note:

Crystal Kirscht wrote:I discovered the same thing. Only it only compiles in Eclipse and in VSCode (which both use Java 17). However when I run Java from the command line on the same code it does not compile. I'm not sure what is different


Can you type


My guess is your command line is using Java 21 and triggering the change in behavior Paul mentioned.
 
Crystal Kirscht
Greenhorn
Posts: 8
1
  • Number of slices to send:
    Optional 'thank-you' note:

Jeanne Boyarsky wrote:

Crystal Kirscht wrote:I discovered the same thing. Only it only compiles in Eclipse and in VSCode (which both use Java 17). However when I run Java from the command line on the same code it does not compile. I'm not sure what is different


Can you type


My guess is your command line is using Java 21 and triggering the change in behavior Paul mentioned.



It is actually on the command line that it is NOT compiling.

D:\MyWorkspace\HelloWorld\src\chapter3>javac PatternMatching.java
PatternMatching.java:38: error: expression type Integer is a subtype of pattern type Integer
               if(value instanceof Integer data) {
                        ^
1 error

D:\MyWorkspace\HelloWorld\src\chapter3>java --version
java 17.0.4.1 2022-08-18 LTS
Java(TM) SE Runtime Environment (build 17.0.4.1+1-LTS-2)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.4.1+1-LTS-2, mixed mode, sharing)

It is in Eclipse and VSCode where it IS compiling. But I know those are using Java 17 as I have not installed any other versions and I have checked the settings in Eclipse (I'm not sure where they are in VSCode). I've attached screenshots of the code and jre settings in eclipse
Eclipse-JRE.png
Eclipse-Screen-Shot.png
 
Greenhorn
Posts: 11
  • Number of slices to send:
    Optional 'thank-you' note:

Fabio Yasuo Yamashita wrote:
It works



No, it does not!

It generates this compiler error:

 
Marshal
Posts: 79392
377
  • Number of slices to send:
    Optional 'thank-you' note:
Your code compiles and runs on JShell, version 21. Which version of Java® are you using?
 
Enrico Giurin
Greenhorn
Posts: 11
  • Number of slices to send:
    Optional 'thank-you' note:

Campbell Ritchie wrote:Which version of Java® are you using?


JDK 17, the version of Java for the OCP 17 exam.
 
Mike Simmons
Master Rancher
Posts: 4905
74
  • Number of slices to send:
    Optional 'thank-you' note:
Paul Anilprem previously pointed out that in Java 17 this is an error, and in Java 21 it is not.  So it's expected that for Java 17 it should error.  We never found out what version the original poster was using... but it's probably not Java 17.

Incidentally, you can get the same error message from jdk 21 or later by setting the language level to 17 - e.g.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic
vceplus-200-125    | boson-200-125    | training-cissp    | actualtests-cissp    | techexams-cissp    | gratisexams-300-075    | pearsonitcertification-210-260    | examsboost-210-260    | examsforall-210-260    | dumps4free-210-260    | reddit-210-260    | cisexams-352-001    | itexamfox-352-001    | passguaranteed-352-001    | passeasily-352-001    | freeccnastudyguide-200-120    | gocertify-200-120    | passcerty-200-120    | certifyguide-70-980    | dumpscollection-70-980    | examcollection-70-534    | cbtnuggets-210-065    | examfiles-400-051    | passitdump-400-051    | pearsonitcertification-70-462    | anderseide-70-347    | thomas-70-533    | research-1V0-605    | topix-102-400    | certdepot-EX200    | pearsonit-640-916    | itproguru-70-533    | reddit-100-105    | channel9-70-346    | anderseide-70-346    | theiia-IIA-CIA-PART3    | certificationHP-hp0-s41    | pearsonitcertification-640-916    | anderMicrosoft-70-534    | cathMicrosoft-70-462    | examcollection-cca-500    | techexams-gcih    | mslearn-70-346    | measureup-70-486    | pass4sure-hp0-s41    | iiba-640-916    | itsecurity-sscp    | cbtnuggets-300-320    | blogged-70-486    | pass4sure-IIA-CIA-PART1    | cbtnuggets-100-101    | developerhandbook-70-486    | lpicisco-101    | mylearn-1V0-605    | tomsitpro-cism    | gnosis-101    | channel9Mic-70-534    | ipass-IIA-CIA-PART1    | forcerts-70-417    | tests-sy0-401    | ipasstheciaexam-IIA-CIA-PART3    | mostcisco-300-135    | buildazure-70-533    | cloudera-cca-500    | pdf4cert-2v0-621    | f5cisco-101    | gocertify-1z0-062    | quora-640-916    | micrcosoft-70-480    | brain2pass-70-417    | examcompass-sy0-401    | global-EX200    | iassc-ICGB    | vceplus-300-115    | quizlet-810-403    | cbtnuggets-70-697    | educationOracle-1Z0-434    | channel9-70-534    | officialcerts-400-051    | examsboost-IIA-CIA-PART1    | networktut-300-135    | teststarter-300-206    | pluralsight-70-486    | coding-70-486    | freeccna-100-101    | digitaltut-300-101    | iiba-CBAP    | virtuallymikebrown-640-916    | isaca-cism    | whizlabs-pmp    | techexams-70-980    | ciscopress-300-115    | techtarget-cism    | pearsonitcertification-300-070    | testking-2v0-621    | isacaNew-cism    | simplilearn-pmi-rmp    | simplilearn-pmp    | educationOracle-1z0-809    | education-1z0-809    | teachertube-1Z0-434    | villanovau-CBAP    | quora-300-206    | certifyguide-300-208    | cbtnuggets-100-105    | flydumps-70-417    | gratisexams-1V0-605    | ituonline-1z0-062    | techexams-cas-002    | simplilearn-70-534    | pluralsight-70-697    | theiia-IIA-CIA-PART1    | itexamtips-400-051    | pearsonitcertification-EX200    | pluralsight-70-480    | learn-hp0-s42    | giac-gpen    | mindhub-102-400    | coursesmsu-CBAP    | examsforall-2v0-621    | developerhandbook-70-487    | root-EX200    | coderanch-1z0-809    | getfreedumps-1z0-062    | comptia-cas-002    | quora-1z0-809    | boson-300-135    | killtest-2v0-621    | learncia-IIA-CIA-PART3    | computer-gcih    | universitycloudera-cca-500    | itexamrun-70-410    | certificationHPv2-hp0-s41    | certskills-100-105    | skipitnow-70-417    | gocertify-sy0-401    | prep4sure-70-417    | simplilearn-cisa    |
http://www.pmsas.pr.gov.br/wp-content/    | http://www.pmsas.pr.gov.br/wp-content/    |