1 // Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file 2 // for details. All rights reserved. Use of this source code is governed by a 3 // BSD-style license that can be found in the LICENSE file. 4 5 // This code is not run directly. It needs to be compiled to dex code. 6 // 'switches.dex' is what is run. 7 8 package switches; 9 10 class Switches { 11 12 public static void packedSwitch(int value) { 13 System.out.print("packedSwitch cases: "); 14 switch (value) { 15 case 0: 16 System.out.print("0 "); 17 case 1: 18 case 2: 19 System.out.print("1 2 "); 20 break; 21 case 3: 22 System.out.print("3 "); 23 break; 24 } 25 System.out.println("after switch " + value); 26 } 27 28 public static void sparseSwitch(int value) { 29 switch (value) { 30 case 0: 31 System.out.println("0 "); 32 case 100: 33 System.out.println("100 "); 34 break; 35 case 200: 36 System.out.println("200 "); 37 break; 38 } 39 System.out.println("after switch " + value); 40 } 41 42 public static void switchWithLocals(int value) { 43 switch (value) { 44 case 0: { 45 int i = 42; 46 System.out.println(" " + i + value); 47 break; 48 } 49 case 2: { 50 double d = 1.0; 51 System.out.println(" " + d + value); 52 break; 53 } 54 } 55 } 56 57 public static void maybePackedSwitch(int value) { 58 switch (value) { 59 case 0: 60 case 1: 61 case 2: 62 case 3: 63 case 4: 64 case 5: 65 case 6: 66 case 7: 67 case 8: 68 case 10: 69 case 11: 70 case 12: 71 case 13: 72 case 14: 73 case 15: 74 case 16: 75 case 17: 76 case 18: 77 case 19: 78 case 20: 79 case 21: 80 System.out.print("0-21 "); 81 break; 82 case 60: 83 System.out.print("60 "); 84 break; 85 } 86 System.out.println("after switch " + value); 87 } 88 89 public static void main(String[] args) { 90 packedSwitch(0); 91 packedSwitch(1); 92 packedSwitch(2); 93 packedSwitch(-1); // No such case, use fallthrough. 94 sparseSwitch(0); 95 sparseSwitch(100); 96 sparseSwitch(200); 97 sparseSwitch(-1); // No such case, use fallthrough. 98 switchWithLocals(0); 99 switchWithLocals(2); 100 maybePackedSwitch(1); 101 maybePackedSwitch(10); 102 maybePackedSwitch(40); // Fallthrough. 103 maybePackedSwitch(60); 104 } 105 } 106