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

Java के Switch Expressions

एक switch expression एक switch है जो एक value वापस देता है, जैसे एक vending machine जो हर button के लिए एक result देती है। यह पुराने style से छोटा और सुरक्षित है।
Syntax
java
result = switch (expression) {
    case value1 -> result1;
    case value2, value3 -> result2;
    default -> defaultResult;
};

Classic Switch vs Switch Expressions

Switch expressions आपको arrow (->) operator का उपयोग करते हुए हर case से सीधे एक value return करने देते हैं, एक ऐसे result में evaluate होते हुए जिसे आप assign या return कर सकते हैं। यह classic switch statements से साफ़ है क्योंकि यह case fall-through को पूरी तरह हटा देता है, साथ ही हर case के आखिर में explicit break statements की ज़रूरत भी।

उदाहरण: Classic Switch vs Switch Expressions

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare day and set it to 3
		int day = 3;
		String name = switch (day) {
			case 1 -> "Monday";
			case 2 -> "Tuesday";
			case 3 -> "Wednesday";
			default -> "Unknown";
		};
		// Print a line to the console
		System.out.println(name);
	}
}

The yield Statement

अगर किसी case के body को एक single expression से ज़्यादा चाहिए, तो उस code को curly braces में wrap करें और वह value specify करने के लिए yield statement का उपयोग करें जो वह block आखिरकार produce करता है। Yield किसी switch expression के block के अंदर वही भूमिका निभाता है जो किसी method के अंदर return निभाता है।

उदाहरण: The yield Statement

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare score and set it to 85
		int score = 85;
		String grade = switch (score / 10) {
			case 10, 9 -> "A";
			case 8 -> {
				// Declare g and set it to "B"
				String g = "B";
				yield g;
			}
			default -> "C";
		};
		// Print a line to the console
		System.out.println(grade);
	}
}

Multiple Case Labels

आप values को commas से अलग करके कई case labels को एक line पर group कर सकते हैं, ताकि कई inputs हर value के लिए body दोहराने के बजाय बिल्कुल वही arrow-case body share करें।

उदाहरण: Multiple Case Labels

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Declare day and set it to 6
		int day = 6;
		String type = switch (day) {
			case 1, 2, 3, 4, 5 -> "Weekday";
			case 6, 7 -> "Weekend";
			default -> "Invalid";
		};
		// Print a line to the console
		System.out.println(type);
	}
}

Exhaustiveness and default

एक switch expression exhaustive होना चाहिए, यानी इसे switch किए जा रहे expression की हर संभव value के लिए account करना होगा। अगर compiler पहले से खुद type से इसे साबित नहीं कर सकता (जैसा यह sealed types या enums के साथ कर सकता है), तो आपको जो भी unmatched रहे उसे cover करने के लिए एक default case देना होगा।

उदाहरण: Exhaustiveness and default

java
public class Main {
	enum Level { LOW, MEDIUM, HIGH }
	public static void main(String[] args) {
		Level level = Level.MEDIUM;
		String msg = switch (level) { // compiler proves exhaustiveness from the enum, no default needed
			case LOW -> "low";
			case MEDIUM -> "medium";
			case HIGH -> "high";
		};
		System.out.println(msg);
	}
}

Dynamic Evaluation

Arrow case labels सिर्फ constant literals तक सीमित नहीं हैं — वे एक value को dynamically compute और return करने के लिए external methods invoke कर सकते हैं, एक switch expression के cases को सिर्फ fixed constants में से चुनने के बजाय arbitrary logic चलाने देते हुए।

उदाहरण: Dynamic Evaluation

java
public class Main {
	static int square(int n) { return n * n; }
	public static void main(String[] args) {
		int code = 2;
		int result = switch (code) {
			case 1 -> 10;
			case 2 -> square(5); // arbitrary method call, not just a constant
			default -> 0;
		};
		System.out.println(result);
	}
}
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. किसी int या String पर switch करते समय default छोड़ देना, जो एक compile error है क्योंकि एक switch expression को हर संभव value cover करनी चाहिए।
  2. किसी switch expression case के block के अंदर return का उपयोग करना, जबकि value yield से produce होनी चाहिए।
  3. एक ही switch में arrow cases (->) और colon cases (:) मिलाना, जिसकी अनुमति नहीं है।

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.