Want some official clarification on a quirk about pattern-matching for instanceof

David Alayachew davidalayachew at gmail.com
Fri Nov 10 16:40:11 UTC 2023


Hello Amber Dev Team,

Someone on StackOverflow raised an excellent question about
Pattern-Matching for instanceof, and I would like to get a response from
one of you to include in the answer. Here is the link.

https://stackoverflow.com/questions/77453336/instanceof-pattern-matching-in-java-not-compiling#77453336

To summarize, the book that they were reading (Java: The Complete
Reference, 12th Edition by Herbert Schildt) had the following quote.

-----QUOTE_START---- (with minor modifications for readability)

```java
Number myOb = Integer.valueOf(9);
int count = 10;

//                 vv---- Conditional AND Operator
if ( (count < 100) && myOb instanceof Integer iObj)
{

    iObj = count;

}
```

The above fragment compiles because the if block will execute only when
both sides of the && are true. Thus, the use of iObj in the if block is
valid. However, a compilation error will result if you tried to use the &
rather than the &&, as shown below.

```java
Number myOb = Integer.valueOf(9);
int count = 10;

//                 v----- Bitwise Logical AND Operator
if ( (count < 100) & myOb instanceof Integer iObj)
{

    iObj = count;

}
```

In this case, the compiler cannot know whether or not iObj will be in scope
in the if block because the right side of the & will not necessarily be
evaluated.

----QUOTE_END----

When compiling the second example, it is exactly as the author says, we get
told that the variable may not necessarily be in scope. Here is the error I
get using OpenJDK 22 Early Access.

```java
$ java --version
openjdk 22-ea 2024-03-19
OpenJDK Runtime Environment (build 22-ea+20-1570)
OpenJDK 64-Bit Server VM (build 22-ea+20-1570, mixed mode, sharing)

$ javac --version
javac 22-ea

$ cat abc.java
public class abc
{


    public static void main(String[] args)
    {

        Number myOb = Integer.valueOf(9);

        int count = 10;

        if ( (count < 100) & myOb instanceof Integer iObj )
        {

            iObj = count;

        }

    }

}

$ javac abc.java
abc.java:15: error: cannot find symbol
                iObj = count;
                ^
  symbol:   variable iObj
  location: class abc
1 error

```

I feel like I have a very good idea of why this might be the case, but I
lack the terminology to put it into words correctly. Could someone help me
out?

Thank you for your time and help!
David Alayachew
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231110/35ca217b/attachment.htm>


More information about the amber-dev mailing list