← Back to Advanced Java Course | Chapter 4: Modern Java Features | Lesson 5 of 12

Java में Pattern Matching

Pattern matching आपको एक step में type जांचने और उसके हिस्से लेने देता है, जैसे किसी package को खोलना और उसका label एक साथ जांचना। यह लंबे check-and-cast code की जगह लेता है।
Syntax
java
if (object instanceof Type variable) {
    // use variable
}

switch (object) {
    case Type variable -> expression;
    default -> expression;
}

Pattern Matching with instanceof

instanceof के लिए pattern matching classic type-check-then-cast pattern को दोनों steps को एक single expression में combine करके सरल बनाता है। instanceof जांचने और फिर अगली line पर अलग से cast करने के बजाय, matched, सही-typed variable check के ही हिस्से के रूप में अपने आप bind हो जाता है।

उदाहरण: Pattern Matching with instanceof

java
public class Main {
	public static void main(String[] args) {
		Object obj = "hello";
		if (obj instanceof String s) { // bound and cast in one step
			System.out.println(s.toUpperCase());
		}
	}
}

Pattern Variable Scope

pattern matching से introduce किया गया pattern variable सिर्फ उन branches के code में scope में माना जाता है जहां type check statically guaranteed सफल हुआ है। यह आपको उस guaranteed region के बाहर गलती से किसी unset या गलत-typed variable को reference करने से रोकता है।

उदाहरण: Pattern Variable Scope

java
public class Main {
	public static void main(String[] args) {
		Object obj = "text";
		if (obj instanceof String s && s.length() > 2) {
			System.out.println(s); // s is only in scope where the check succeeded
		}
	}
}

Pattern Matching in Switch

Pattern matching switch statements और switch expressions के अंदर भी उपयोग किया जा सकता है, एक single switch को किसी variable को कई अलग-अलग classes से match करने देते हुए और हर संबंधित case के अंदर इसे अपने आप matched type में cast करते हुए।

उदाहरण: Pattern Matching in Switch

java
// Define the class Main
public class Main {
	static String describe(Object obj) {
		// Send switch (obj) { back to the caller
		return switch (obj) {
			case Integer i -> "Integer: " + i;
			case String s -> "String: " + s;
			default -> "Unknown";
		};
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(describe(42));
	}
}

Switch Patterns with Guards

आप when keyword का उपयोग करके individual switch cases में conditional checks जोड़ सकते हैं, जिन्हें guards कहा जाता है। यह आपको एक single pattern-matched case के अंदर filter करने देता है, उदाहरण के लिए एक specific class को तभी match करते हुए जब इसके किसी field के साथ एक अतिरिक्त condition भी satisfy हो।

उदाहरण: Switch Patterns with Guards

java
// Define the class Main
public class Main {
	static String classify(Object obj) {
		// Send switch (obj) { back to the caller
		return switch (obj) {
			case Integer i when i > 100 -> "Big integer";
			case Integer i -> "Small integer";
			default -> "Not an integer";
		};
	}
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println(classify(500));
	}
}

Record Patterns

Record patterns आपको किसी record object को किसी type check के हिस्से के रूप में सीधे destructure करने देते हैं, तुरंत इसके individual component fields को local variables के रूप में उजागर करते हुए। यह record के type को match करने और फिर अलग से इसके accessor methods call करने के अतिरिक्त step से बचाता है।

उदाहरण: Record Patterns

java
public class Main {
	record Point(int x, int y) {}
	public static void main(String[] args) {
		Object obj = new Point(3, 4);
		if (obj instanceof Point(int x, int y)) { // deconstructed directly
			System.out.println(x + "," + y);
		}
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. match के सफल होने की गारंटी वाले branch के बाहर pattern variable का उपयोग करना, जैसे if (!(obj instanceof String s)) के बाद, जो 'cannot find symbol' error देता है।
  2. case String s जैसे specific case से पहले case Object o जैसा general case रखना, जो compile error है क्योंकि बाद वाला case dominated है।
  3. किसी case null के बिना pattern switch को null पास करना, जो NullPointerException फेंकता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.