> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Java Type Pattern

A type pattern is a language construct in Java that combines type checking and conditional extraction into a single operation. It consists of a predicate that tests whether a target object matches a specific type and, upon a successful match, automatically casts and binds the target to a newly declared local variable, known as a pattern variable.

## Syntax

A type pattern consists of a type name followed by a variable declaration:

```java theme={"dark"}
TargetType patternVariable
```

## Mechanics in `instanceof`

Introduced in Java 16, type patterns eliminate the need for explicit casting after an `instanceof` check. If the runtime type of the target object is assignment-compatible with the `TargetType`, the pattern matches, and the `patternVariable` is initialized with the casted value.

```java theme={"dark"}
// Traditional type checking and casting
if (obj instanceof String) {
    String s = (String) obj; 
    System.out.println(s.length());
}

// Type pattern matching
if (obj instanceof String s) {
    System.out.println(s.length());
}
```

## Mechanics in `switch`

Standardized in Java 21, type patterns can be used as `case` labels within `switch` statements and expressions. This allows a `switch` block to route execution based on the runtime type of the selector expression.

```java theme={"dark"}
Object obj = "Hello";

switch (obj) {
    case String s  -> System.out.println("String of length: " + s.length());
    case Integer i -> System.out.println("Integer value: " + i);
    case null      -> System.out.println("Null reference");
    default        -> System.out.println("Unmatched type");
}
```

## Flow Scoping

Pattern variables utilize **flow scoping** (or flow-sensitive typing). The scope of a pattern variable is strictly limited to the execution paths where the compiler can definitively prove that the pattern has matched.

**Short-circuit evaluation:**

```java theme={"dark"}
// 's' is in scope on the right side of the && operator 
// because it only evaluates if the pattern match succeeds.
if (obj instanceof String s && s.length() > 5) {
    System.out.println(s);
}

// Compilation Error: 's' is NOT in scope on the right side of the || operator
// because the right side evaluates only if the pattern match fails.
if (obj instanceof String s || s.length() > 5) { }
```

**Inverted scoping:**

```java theme={"dark"}
public void process(Object obj) {
    if (!(obj instanceof String s)) {
        return; // Execution halts if the pattern fails
    }
    
    // 's' is in scope for the remainder of the method block
    // because reaching this point guarantees the pattern matched.
    System.out.println(s.toUpperCase());
}
```

## Guarded Patterns

Type patterns in `switch` blocks can be refined using the `when` keyword to apply additional boolean conditions, known as guards. The pattern variable is in scope within the `when` clause.

```java theme={"dark"}
switch (obj) {
    case String s when s.length() > 10 -> System.out.println("Long string");
    case String s                      -> System.out.println("Short string");
    default                            -> System.out.println("Not a string");
}
```

*Note: Pattern dominance rules apply. A guarded type pattern must appear before an unguarded type pattern of the same type, otherwise the compiler will throw an unreachable code error.*

## Nullability Rules

* **`instanceof`:** A type pattern will never match a `null` reference. If `obj` is `null`, `obj instanceof String s` evaluates to `false`, and `s` is not initialized.
* **`switch`:** A type pattern `case String s` will not match a `null` selector expression. To handle `null` in a pattern-matching switch, an explicit `case null` must be provided, or it can be combined with a type pattern using `case null, String s`.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Java Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
