Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8213180

5.6.3: byte result expression in switch widens to char, but should widen to int

    Details

      Description

      Following behavior of compiler is not as per spec.

      1. In switch expression byte type is promoted to integer type when all other result expression is of type char.

      According to spec section 5.6.3 Switch Numeric Promotion:
      "Otherwise, if any result expression is of type char, and every other result expression is either of type char, or of type byte, or a constant expression of type int with a value that is representable in the type char, then the byte results are widened to char and the int results are narrowed to char."

      Sample Code:
      public class SwitchTest {
          public static void main(String[] args) {

              STest st = new STest();
              System.out.println(st.check());
          }
      }

      class STest {
          private int i = 0;

          public String check() {
              char charValue = 'a';
              byte byteValue = (byte)10;

              var promoted = switch (i + 1) {
                  case 1 ->byteValue;
                  case 5 ->charValue;
                  default ->charValue;
              } ;


              return checkType(promoted);
          }

          private String checkType(char data) { return "char"; }

          private String checkType(byte data) { return "byte"; }

          private String checkType(int data) { return "int"; }
      }

      output: int

      The output of the above code is "int", which reflects that the byteValue which is of type byte was promoted to integer type however according to switch expression spec of section 5.6.3 the byte type should be widened to char type. Also, with above mention spec numeric promotion behavior is not clear in case of byte value representing negative numbers.

        Attachments

          Activity

            People

            • Assignee:
              gbierman Gavin Bierman
              Reporter:
              rchandra Ravi Chandra
            • Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: