Skip to content

Commit 5e8076d

Browse files
myluckagainpivovarit
authored andcommitted
BAEL-2182 (eugenp#5257)
* BAEL-2182 * refactoring
1 parent 991d693 commit 5e8076d

2 files changed

Lines changed: 108 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

0 commit comments

Comments
 (0)