-2

I have this class, of a problem that I can't understand yet. I have some questions.

  • Where java cast char to int (I know char is numeric type, but in the switch cases I have int and char values)
  • Why case 1 not executed if switch postincrement set 1 value in the "i" variable. I think i value is 1 in the first iteration due the ++ operator.
  • Why case 2 is executed first or How i get 2 value without get 1 before? I see the default of the first iteration print 1.

This is the code:

public class ForSwitch {
    public static void main(String args[]) {
        char i;
        LOOP: for (i = 0; i < 5; i++) {
            System.out.println("For: i value: " + (int) i);
            switch (i++) {
            case '0':System.out.println("A");
            case 1:System.out.println("B");break LOOP;
            case 2:System.out.println("C");break;
            case 3:System.out.println("D");break;
            case 4:System.out.println("E");
            case 'E':System.out.println("F");
            default:System.out.println("Switch: i value: " + (int) i);
            }
        }
    }
}

Output is this:

For: i value: 0
Switch: i value: 1
For: i value: 2
C
For: i value: 4
E
F
Switch: i value: 5
Genaut
  • 1,810
  • 2
  • 29
  • 60
  • `1 != '1'`. Try printing both of them: `int a = 1; int b = '1'; System.out.printf("%d %d", a, b);`. – Andy Turner Jul 03 '17 at 12:18
  • You are incrementing your i counter twice per loop. Don't switch on `i++`, just use `switch(i)`. The incrment already happens in the for loop. And if you meant to do that consider that i++ will increment evaluating the switch statement. See: https://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java – OH GOD SPIDERS Jul 03 '17 at 12:19
  • `switch (i++)` -> uses the "old" value of `i` to decide which `case` is used, then increments `i` – UnholySheep Jul 03 '17 at 12:20
  • @AndyTurner How you can see, switch have case 1, not case '1'. – Genaut Jul 03 '17 at 13:16
  • OK, so exactly the same with `'0'` and `0` instead of `'1'` and `1`. – Andy Turner Jul 03 '17 at 13:17
  • Yes, but I dont ask about these diferences :) – Genaut Jul 03 '17 at 13:18

1 Answers1

2

it equivalent of

for (int i = 0; i < 5; i = i + 1) {
    int j = i;
    i = i + 1;
    switch (j) {
        case 48: System.out.println("A");
        case 1: System.out.println("B");break LOOP;
...
rustot
  • 331
  • 1
  • 11
  • Thanks @rustot, I think that I can see the "path" now, anyway I have a little question about this yet. Why the first iteration print in the default value 1 but don't execute the 1 case? Could be that case sentence compare with the i value before the increment, but the use of the i var is incremented? Sorry my english – Genaut Jul 03 '17 at 13:24
  • in first loop j == 0 (therefore it jump to 'default' branch), but i == 1 (and it printed in 'default') – rustot Jul 03 '17 at 14:50