Skip to content

Commit 59f3573

Browse files
authored
Added a new Class and few test cases to the core-java-modules (eugenp#11867)
* added a new project: hexagonal architecture * Added some test cases for the project * Added a new project to demo the error: variable might not have been initialized * Added a new Class to the core-java-modules * Added a New Class to the core-java-module
1 parent 440f4e4 commit 59f3573

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.baeldung.exception.variablemightnothavebeeninitialized;
2+
3+
public class VariableMightNotHaveBeenInitialized {
4+
5+
private static int instanceVariableCount;
6+
7+
/**
8+
* Method would not compile if lines 14 and 18 are uncommented.
9+
*/
10+
public static void countEven() {
11+
//uninstantiated
12+
int count;
13+
int[] arr = new int[]{23, 56, 89, 12, 23};
14+
for (int i = 0; i < arr.length; i++) {
15+
if ((arr[i] % 2) == 0) {
16+
// count++;
17+
}
18+
19+
}
20+
// System.out.println("Total Even Numbers : " + count);
21+
}
22+
23+
public static int countEvenUsingInstanceVariable(int[] arr) {
24+
25+
for (int i = 0; i < arr.length; i++) {
26+
if ((arr[i] % 2) == 0) {
27+
instanceVariableCount++;
28+
}
29+
30+
}
31+
return instanceVariableCount;
32+
}
33+
34+
public static int countEvenUsingIfElse(int[] arr, int args) {
35+
int count;
36+
count = args > 0 ? args : 0;
37+
for (int i = 0; i < arr.length; i++) {
38+
if ((arr[i] % 2) == 0) {
39+
count++;
40+
}
41+
42+
}
43+
return count;
44+
}
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.baeldung.exception.variablemightnothavebeeninitialized;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class VariableMightNotHaveBeenInitializedUnitTest {
8+
9+
@Test
10+
public void usingInstanceVariable_returnCount() {
11+
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
12+
int value = VariableMightNotHaveBeenInitialized.countEvenUsingInstanceVariable(arr);
13+
14+
assertEquals(3, value);
15+
}
16+
17+
@Test
18+
public void usingArgumentsAndIfElse_returnCount() {
19+
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
20+
int value = VariableMightNotHaveBeenInitialized.countEvenUsingIfElse(arr, 2);
21+
22+
assertEquals(5, value);
23+
}
24+
}

0 commit comments

Comments
 (0)