Java - control switch -switch statement


#1

public class Switch {
public static void main(String[] args) {

	char penaltyKick = 'R';

	switch (penaltyKick) {

		case 'L': System.out.println("Messi shoots to the left and scores!");
							 
		case 'R': System.out.println("Messi shoots to the right and misses the goal!");
						
		case 'C': System.out.println("Messi shoots down the center, but the keeper blocks it!");
							
		default:
			System.out.println("Messi is in position");

	}

}

}

I've removed all the break statements.
why the above code executes statements next to case R, case C and default case.

I think it should execute Case R and Default case not case C


#2

My friend you should not remove the "break" statement. The system will print out the case that is equal to the variable. So it should only choses one case at the time. If you remove the break then it will choses more cases at the same time. And to answer your question to why it not choses the 'L' case is because of the swich is in operation. because of the "switch if will execute at least one case.

The char that you make equal to your variable... will print out the case that is equal to the variable

example:

if your variable is: char penaltyKick = 'R' ;

then it choses: Case 'R' : System.out.println("Messi shoots to the right and misses the goal!");

this will be printed to the console


#3

But if u run it and char penaltyKick='R'
It prints all the cases starting from case 'R' to default case.
Please try to run the code by removing every break statement & setting
penaltyKick='R'.

I think with above changes it should print:-

Messi shoots to the right and misses the goal!

Messi is in position

Thank You for helping me.