File tree Expand file tree Collapse file tree
main/java/com/baeldung/switchstatement
test/java/com/baeldung/switchstatement Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .switchstatement ;
2+
3+ public class SwitchStatement {
4+
5+ public String exampleOfIF (String animal ) {
6+
7+ String result ;
8+
9+ if (animal .equals ("DOG" ) || animal .equals ("CAT" )) {
10+ result = "domestic animal" ;
11+ } else if (animal .equals ("TIGER" )) {
12+ result = "wild animal" ;
13+ } else {
14+ result = "unknown animal" ;
15+ }
16+ return result ;
17+ }
18+
19+ public String exampleOfSwitch (String animal ) {
20+
21+ String result ;
22+
23+ switch (animal ) {
24+ case "DOG" :
25+ case "CAT" :
26+ result = "domestic animal" ;
27+ break ;
28+ case "TIGER" :
29+ result = "wild animal" ;
30+ break ;
31+ default :
32+ result = "unknown animal" ;
33+ break ;
34+ }
35+ return result ;
36+ }
37+
38+ public String forgetBreakInSwitch (String animal ) {
39+
40+ String result ;
41+
42+ switch (animal ) {
43+
44+ case "DOG" :
45+ System .out .println ("domestic animal" );
46+ result = "domestic animal" ;
47+
48+ default :
49+ System .out .println ("unknown animal" );
50+ result = "unknown animal" ;
51+
52+ }
53+ return result ;
54+ }
55+
56+ public String constantCaseValue (String animal ) {
57+
58+ String result = "" ;
59+
60+ final String dog = "DOG" ;
61+
62+ switch (animal ) {
63+
64+ case dog :
65+ result = "domestic animal" ;
66+ }
67+ return result ;
68+ }
69+
70+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .switchstatement ;
2+
3+ import org .junit .Test ;
4+
5+ import org .junit .Assert ;
6+
7+ public class SwitchStatementUnitTest {
8+ private SwitchStatement s = new SwitchStatement ();
9+
10+
11+ @ Test
12+ public void whenDog_thenDomesticAnimal () {
13+
14+ String animal = "DOG" ;
15+ Assert .assertEquals ("domestic animal" , s .exampleOfSwitch (animal ));
16+ }
17+
18+ @ Test
19+ public void whenNoBreaks_thenGoThroughBlocks () {
20+ String animal = "DOG" ;
21+ Assert .assertEquals ("unknown animal" , s .forgetBreakInSwitch (animal ));
22+ }
23+
24+ @ Test (expected =NullPointerException .class )
25+ public void whenSwitchAgumentIsNull_thenNullPointerException () {
26+ String animal = null ;
27+ Assert .assertEquals ("domestic animal" , s .exampleOfSwitch (animal ));
28+ }
29+
30+
31+ @ Test
32+ public void whenCompareStrings_thenByEqual () {
33+ String animal = new String ("DOG" );
34+ Assert .assertEquals ("domestic animal" , s .exampleOfSwitch (animal ));
35+ }
36+
37+
38+ }
You can’t perform that action at this time.
0 commit comments