-1

I am trying to learn the break function in java , for example this following code:

Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int num = in.nextInt();
switch (num) { // switching values for num
case 1: // if num is 1 
    System.out.println("1");
    break; // stop here and don't continue.
case 2: // if num is 2
    System.out.println("F");
    break; // stop here and don't continue
default: // if all cases are wrong
    System.out.println("R");
    break; //finish
}

So my question is for example, if I am deleting the break after case 1, why does it print "F"? also if there is no break there, it's still supposed to check if num=2 in the line case 2: , so, why without break in case 1: , it skips to case 2 without checking if it is true and doing what is inside of it?

Guy Balas
  • 98
  • 3
  • 10
  • 3
    This is how `break` works. Take a look at the following tutorial from Oracle: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html – Tunaki Sep 06 '15 at 19:06

2 Answers2

1

The comparison happens only once, at the beginning; it doesn't re-compare for every case.

Without break it falls through to the next case's statements, but it does not re-compare.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

You may want to check the offficial tutorial, where this is explained in a very good detail.

Citing the part related to your question:

Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

Sva.Mu
  • 1,141
  • 1
  • 14
  • 24