Julia Julia - 7 months ago 10
Java Question

Java: What's the point of Char to Int conversion and then comparison Int to Char? And why does this work?

I'm reading Java-book. There is a code that I don't get. Why are we saving result in INT if we need to compare to CHAR anyway? And why does this work properly?

public static char getChar() throws IOException
{
String s = getString();
return s.charAt(0);
}
int choice = getChar();

switch(choice)
{
case 's': {}
case 'r': {}
case 'n': {}
case 'g': {}
case 'b': {}
case 'a': {}
case 'd': {}
default: {}
}

Answer

There is no difference between using char and int literals in the switch:

public static void withCharLiteral() {
  int choice = getChar();
  switch (choice) {
    case 's':
      break;
  }
}

Compiles to:

  public static void withCharLiteral();
    Code:
       0: invokestatic  #2                  // Method getChar:()C
       3: istore_0
       4: iload_0
       5: lookupswitch  { // 1
                   115: 24
               default: 24
          }
      24: return

vs with an int literal:

public static void withIntLiteral() {
  int choice = getChar();
  switch (choice) {
    case 115:
      break;
  }
}

Compiles to:

  public static void withIntLiteral();
    Code:
       0: invokestatic  #2                  // Method getChar:()C
       3: istore_0
       4: iload_0
       5: lookupswitch  { // 1
                   115: 24
               default: 24
          }
      24: return

All char can be converted to int, even the ones you use in switch cases. As such, it is just a question of preference/convenience/readability as to whether you use the char or int literal form.

Comments