Can any one expain how the following program works?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • itiger
    New Member
    • Sep 2010
    • 12

    Can any one expain how the following program works?

    Code:
    class SwitchTest
    {
    	public static void main(String args[])
    	{
    		int x = 5;
    		switch(x)
    		{
    			case 1:
    				System.out.println("In 1st case");
    			return ;
    			case 3:
    				System.out.println("In 3rd case");
    			return ;
    			case 5:
    				System.out.println("In 5th case");
    			return ;
    			case 7:
    				System.out.println("In 7th case");
    			return ;
    			default:
    				System.out.println("In default case");
    		}
    		System.out.println("Out of switch");
    	}
    }
    Output:
    In 5th case

    What does return keyword returning here. Main() is not returning anything (void), So how the program is running without any error even though we are retuning something in switch.
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    You are returning in the switch statement. That is perfectly alright. Return statement returns the control to the caller. In this case with out any value.

    In this program case 5 is matching value. So it prints and returns the control.

    If you take x as 8 then the output will be
    Code:
    In default case
    Out of switch
    Why you are expecting any errors in this code?

    Regards
    Dheeraj Joshi

    Comment

    Working...