Added a new Class and few test cases to the core-java-modules (#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
This commit is contained in:
parent
eae57f5496
commit
e10e20a24b
|
@ -0,0 +1,45 @@
|
||||||
|
package com.baeldung.exception.variablemightnothavebeeninitialized;
|
||||||
|
|
||||||
|
public class VariableMightNotHaveBeenInitialized {
|
||||||
|
|
||||||
|
private static int instanceVariableCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method would not compile if lines 14 and 18 are uncommented.
|
||||||
|
*/
|
||||||
|
public static void countEven() {
|
||||||
|
//uninstantiated
|
||||||
|
int count;
|
||||||
|
int[] arr = new int[]{23, 56, 89, 12, 23};
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
if ((arr[i] % 2) == 0) {
|
||||||
|
// count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
// System.out.println("Total Even Numbers : " + count);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int countEvenUsingInstanceVariable(int[] arr) {
|
||||||
|
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
if ((arr[i] % 2) == 0) {
|
||||||
|
instanceVariableCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return instanceVariableCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int countEvenUsingIfElse(int[] arr, int args) {
|
||||||
|
int count;
|
||||||
|
count = args > 0 ? args : 0;
|
||||||
|
for (int i = 0; i < arr.length; i++) {
|
||||||
|
if ((arr[i] % 2) == 0) {
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,24 @@
|
||||||
|
package com.baeldung.exception.variablemightnothavebeeninitialized;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
public class VariableMightNotHaveBeenInitializedUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void usingInstanceVariable_returnCount() {
|
||||||
|
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
|
||||||
|
int value = VariableMightNotHaveBeenInitialized.countEvenUsingInstanceVariable(arr);
|
||||||
|
|
||||||
|
assertEquals(3, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void usingArgumentsAndIfElse_returnCount() {
|
||||||
|
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
|
||||||
|
int value = VariableMightNotHaveBeenInitialized.countEvenUsingIfElse(arr, 2);
|
||||||
|
|
||||||
|
assertEquals(5, value);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue