javainstanceofjava-17

Java Pattern Variable Scope


I am going through Oracle's official docs to understand Pattern Variable scope in Java 17. In the following example, the method testScope1 works as explained in the docs, but the method testScope2 gives a compilation error. I am not able to figure out why void return type of the method is causing the issue?

interface Vehicle{}
class Car implements Vehicle{}

class Pattern{
    public int testScope1(Vehicle v){
        if(!(v instanceof Car c)){
            return 1;
        }
        System.out.println(c.toString());  //WORKS FINE
        return 2; 
    }
    public void testScope2(Vehicle v){
        if(!(v instanceof Car c)){
                 
        }
        System.out.println(c.toString());  //COMPILE TIME ERROR: Cannot resolve symbol c
    }
}

Solution

  • Think about what happens if v is not a Car instance: