Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Rewrite in Java 17 style:

Java
if (shape instanceof Circle) {
Circle c = (Circle) shape;
return Math.PI * c.r() * c.r();
} else if (shape instanceof Square) {
Square s = (Square) shape;
return s.side() * s.side();
}
throw new IllegalStateException();

In Java 17 we use pattern matching for instanceof, so each test also declares the variable: if (shape instanceof Circle c) return Math.PI * c.r() * c.r();. In Java 21 a switch with type patterns is clearer still: return switch (shape) { case Circle c -> Math.PI * c.r() * c.r(); case Square s -> s.side() * s.side(); };. If Shape is a sealed interface that permits only Circle and Square, the switch needs no default, the compiler checks that it is exhaustive, and adding a new permitted subtype causes compile errors wherever a switch does not handle it.

Why this question is asked

This small rewrite shows three Java features working together, and it is one of the clearest ways to show an interviewer that we write modern Java rather than Java 8 on a newer JVM. It also contains a design point: replacing a runtime exception with a compile-time check. In this answer, we will look at what is wrong with the original code, rewrite it with Java 17 pattern matching, then with a Java 21 switch, make Shape sealed so the compiler checks exhaustiveness, and see what happens when a new shape is added.

1What the Original Code Does and Why It Is Clumsy

The original code tests the type of shape, then casts it to that type into a new variable, then uses it. Each branch says the type name three times: in the instanceof, in the cast and in the variable declaration. If someone edits the test but not the cast, the code compiles and fails with a ClassCastException at run time.

The final throw is also a warning sign. It exists because the compiler has no idea which kinds of Shape exist, so we must handle the case of an unknown one at run time. If a developer adds Triangle next year, nothing tells them this method needs updating; it will simply throw IllegalStateException in production.

Java
// Original, Java 8 style
double area(Shape shape) {
if (shape instanceof Circle) {
Circle c = (Circle) shape;
return Math.PI * c.r() * c.r();
} else if (shape instanceof Square) {
Square s = (Square) shape;
return s.side() * s.side();
}
throw new IllegalStateException();
}

2Java 17: Pattern Matching for instanceof

Pattern matching for instanceof, final since Java 16, combines the test and the cast. shape instanceof Circle c checks the type and, if it matches, declares c already typed as Circle. The variable is only in scope where the test is known to be true.

Java
double area(Shape shape) {
if (shape instanceof Circle c) return Math.PI * c.r() * c.r();
if (shape instanceof Square s) return s.side() * s.side();
throw new IllegalStateException("unknown shape: " + shape);
}
area(new Circle(1)); // 3.141592653589793
area(new Square(3)); // 9.0

Notice that the casts are gone, so the test and the variable can no longer disagree. The method is shorter, but it still needs the throw at the end, because the compiler still does not know the full set of shapes. In Java 17 a switch over types was only a preview feature, so this is the best fully supported Java 17 version.

3Java 21: A Switch With Type Patterns

Pattern matching for switch became final in Java 21. Each case label is a type pattern, and the switch expression returns the value of the matching case.

Java
double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.r() * c.r();
case Square s -> s.side() * s.side();
};
}
// With a non-sealed Shape this does not compile:
// error: the switch expression does not cover all possible input values

Notice the compile error. A switch expression must be exhaustive: it must produce a value for every possible input. If Shape is an ordinary interface, any class could implement it, so the compiler demands a default branch. We could add default -> throw new IllegalStateException(), but that brings back the same weakness as before.

4Making Shape Sealed

A sealed interface lists, with permits, the only classes allowed to implement it. Records are implicitly final, so they are perfect permitted subtypes. Now the compiler knows that every Shape is either a Circle or a Square.

Java
sealed interface Shape permits Circle, Square {}
record Circle(double r) implements Shape {}
record Square(double side) implements Shape {}
double area(Shape shape) {
return switch (shape) { // exhaustive: compiles with no default
case Circle c -> Math.PI * c.r() * c.r();
case Square s -> s.side() * s.side();
};
}
// Java 21 record patterns can unpack the components directly
double area2(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Square(double side) -> side * side;
};
}
The same method across versions
VersionStyleUnknown shape found
Java 8instanceof plus castAt run time, IllegalStateException
Java 17instanceof patternAt run time, IllegalStateException
Java 21, open interfaceswitch with defaultAt run time, from default
Java 21, sealed interfaceswitch, no defaultAt compile time

Notice that there is no default and no throw. The compiler proved that every case is handled. A null shape still throws NullPointerException from the switch, unless we add case null explicitly, which is the same behaviour as before.

5Adding a New Shape

The payoff appears when the model changes. Suppose we add Triangle to the permits list. Every switch over Shape that has no default stops compiling, and the error points to it.

Java
sealed interface Shape permits Circle, Square, Triangle {}
record Triangle(double base, double height) implements Shape {}
// area(...) now fails to compile:
// error: the switch expression does not cover all possible input values
case Triangle t -> 0.5 * t.base() * t.height(); // add this case

This is why we avoid a default in switches over sealed types: a default would silently swallow Triangle. The compiler becomes a checklist of every place that needs updating, which is far better than discovering it in production.

6Follow-up questions

Why not just add an abstract area() method to Shape?

That is the classic object-oriented answer, and it is good when the operation belongs to the shape. Pattern matching is better when operations are many and live outside the types, such as rendering, serialising or pricing, and we do not want every new operation to change every record. With sealed types, both approaches are safe.

Does the order of cases matter?

Yes, when patterns overlap. A more general pattern before a more specific one is a compile error because the specific case could never match. Circle and Square do not overlap, so their order does not matter here.

What does the compiler generate for a pattern switch?

It uses an invokedynamic call to a bootstrap method in java.lang.runtime.SwitchBootstraps, which chooses the matching case efficiently. We do not need to know the details, but it means the switch is not a chain of instanceof tests that gets slower with more cases.

7Conclusion

In this answer, we rewrote the method in three steps. Java 17's pattern matching for instanceof removed the casts, but still needed a throw for unknown shapes. Java 21's switch with type patterns made the code clearer, and with a sealed Shape that permits only Circle and Square the switch needs no default because the compiler proves it exhaustive. Adding a new permitted subtype then becomes a compile error in every switch that does not handle it, which turns a production exception into a build failure.

What to say in the interviewAbout 90 seconds aloud

Open with

In Java 17 I would use pattern matching for instanceof, which tests and casts in one step: if shape instanceof Circle c, return pi times c.r() squared, and if shape instanceof Square s, return the side squared.

Then, if they want more

That removes the casts and the risk of the test and cast disagreeing, but it still needs the throw at the end, because the compiler does not know which shapes exist. In Java 21 I would go further and write a switch expression with type patterns: case Circle c arrow the circle area, case Square s arrow the square area.

A switch expression must be exhaustive, so with an ordinary interface the compiler would demand a default. The real improvement is making Shape a sealed interface that permits only Circle and Square, ideally both as records.

Then the compiler knows every possible subtype, the switch compiles with no default and no throw, and I can even use record patterns like case Circle(double r). The best part is what happens when someone adds Triangle to the permits clause: every switch over Shape without a default stops compiling, pointing exactly to the places that need a new case.

So an IllegalStateException in production becomes a compile error, and that is why I avoid adding a default to switches over sealed types.

About this answer

Last updated
12 November 2026
Versions it names
Java 17, Java 21, Java 8, Java 16
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Rewrite in Java 17 style:": https://scrivio-interview-library.netlify.app/java/java-versions/dd15901f4f/