Difference between Yield and Return in Switch statement

In the context of Java switch expressions, both yield and return relate to producing a value, but they serve distinct purposes and behave differently within a switch. Let’s break down the differences in detail, focusing on their roles in switch expressions versus traditional switch statements.

Key Concepts:

  • return: A keyword used to exit a method and optionally return a value to the caller. It’s been part of Java since the beginning and works in any method context, including inside traditional switch statements.
  • yield: A keyword introduced specifically for switch expressions to produce a value from a block within the switch. It’s not a method-level exit; it’s local to the switch expression’s block.

Differences Between yield and return in Switch:

1. Purpose and Scope

  • return:
    • Exits the entire method, not just the switch.
    • Used in traditional switch statements or anywhere in a method to terminate execution and send a value back to the caller.
    • Cannot be used directly in a switch expression to define its result (it bypasses the expression’s mechanics).
  • yield:
    • Produces a value for the switch expression itself, without exiting the enclosing method.
    • Used only within a switch expression’s block (with colon : syntax or -> blocks) to specify the result of that case.

2. Context of Use

  • return:
    • Works in traditional switch statements (pre-Java 14) or anywhere in a method.
    • Not tied to switch expressions specifically.
  • yield:
    • Exclusive to switch expressions (introduced in Java 14).
    • Required when a block in a switch expression needs to compute and return a value.

3. Behavior in Switch Expressions

  • return:
    • If used inside a switch expression, it exits the entire method, bypassing the switch expression’s ability to assign a value.
    • This makes it incompatible with the design of switch expressions, which are meant to evaluate to a single value.
  • yield:
    • Stays within the switch expression’s flow, providing the value that the expression evaluates to.
    • Think of it as “returning” a value to the switch expression, not the method.

4. Syntax Compatibility

  • return:
    • Used in traditional switch statements with colon (:) syntax and break.
    • Not valid in the -> (arrow) syntax of switch expressions.
  • yield:
    • Used in switch expressions with colon (:) syntax or in blocks with ->.
    • Not valid outside of switch expressions (e.g., you can’t use yield in a regular method).

Examples to Illustrate:

1. Traditional Switch Statement with return

public String getDayType(String day) {
    switch (day) {
        case "Monday":
            return "Weekday"; // Exits the method immediately
        case "Saturday":
            return "Weekend"; // Exits the method immediately
        default:
            return "Invalid"; // Exits the method immediately
    }
}
  • Here, return exits the getDayType method entirely, returning the value to the caller.
  • No need for break because return terminates execution.

2. Switch Expression with yield

public String getDayType(String day) {
    return switch (day) {
        case "Monday":
            yield "Weekday"; // Produces value for the switch expression
        case "Saturday":
            yield "Weekend"; // Produces value for the switch expression
        default:
            yield "Invalid"; // Produces value for the switch expression
    };
}
  • yield provides the value for the switch expression, which is then returned by the method via the outer return.
  • The switch expression evaluates to a single value that’s assigned or returned.

3. Switch Expression with -> (No yield Needed)

public String getDayType(String day) {
    return switch (day) {
        case "Monday" -> "Weekday";   // Direct value, no yield needed
        case "Saturday" -> "Weekend"; // Direct value, no yield needed
        default -> "Invalid";         // Direct value, no yield needed
    };
}
  • With ->, you don’t use yield unless the case has a block {} with multiple statements.

4. Switch Expression with Block and yield

public String getDayType(String day) {
    return switch (day) {
        case "Monday" -> {
            System.out.println("Checking Monday");
            yield "Weekday"; // Required to produce the value
        }
        case "Saturday" -> "Weekend";
        default -> "Invalid";
    };
}
  • Inside a block {} with ->, yield is mandatory to specify the result.

5. Misusing return in Switch Expression (Won’t Work as Expected)

public String getDayType(String day) {
    String result = switch (day) {
        case "Monday" -> {
            return "Weekday"; // Exits method, bypasses assignment to result
        }
        case "Saturday" -> "Weekend";
        default -> "Invalid";
    };
    System.out.println("This won’t print if return is hit");
    return result;
}
  • If “Monday” is matched, return “Weekday” exits the method immediately, and result is never assigned. This defeats the purpose of the switch expression.

Why yield Instead of return in Switch Expressions?

  • Design Intent: Switch expressions are meant to be expressions that evaluate to a value, not control-flow statements that exit methods. yield keeps the focus on producing a value for the expression.
  • Consistency: return already has a well-defined meaning (exit the method), so introducing yield avoids confusion and aligns with other languages like Python (where yield is used in generators).
  • Block Support: yield allows multi-statement blocks within a switch expression while maintaining its role as an expression.

Real-time Example:

package java17;


public class SwichExpressionExample {
public static void main(String[] args) {
	System.out.println("Add Two Elements : "+action(145,13,"Add")); ;
	System.out.println("Multiply Two Elements : "+action(145,13,"M")); ;
	System.out.println("Find the Day : "+findTheDay("Friday") );
	System.out.println("Switch with Return : "+action(10) );
}
//Switch with Break
static String action(int value) {
	switch (value) {
	case 10: return "Ten";
	case 5: return "Five";	 
	default: return "Zero";
	}
	//System.out.println("Printing outside of the Switch"); //UnReachable Code
}


//Switch with yield
static int action(int a,int b,String actionType) {
	int output = 0;
	
 output =	switch(actionType) {
		case "Add","A" : 
		    yield  (a + b);
		case "Multiply","M" :
			yield  (a * b);
		case "Divide","D" :
			yield  (a / b);
		case "Substract","S":
			yield  (a - b);
		default  :
			yield 0;
	};
	System.out.println("Printing the data outside of the Switch statement");
	
	return output ;
}

//Switch without yield (With Lambda)
static String findTheDay(String day) {
	String output = "";
	output = switch (day) {
	case "Monday","Tuesday","Wednesday","Thursday","Friday" -> "Weekday";
	case "Saturday","Sunday" -> "Weekend";
	default -> "Invalid Day";
	};
	return output;
}
}

Output:

Summary Table:

Featurereturnyield
PurposeExits method, returns valueProduces value for switch expr
ScopeEntire methodSwitch expression block
Switch TypeTraditional switch statementSwitch expression
SyntaxAny method, no -> in expr: or -> blocks in expr
Exits Method?YesNo
IntroducedJava 1.0Java 14 (for switch expr)

Practical Takeaway:

  • Use return in traditional switch statements or when you want to exit a method directly.
  • Use yield in switch expressions when a block needs to compute a value, especially with colon (:) syntax or -> blocks.
  • For simple cases with ->, you don’t need either—just provide the value directly.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *