diff --git a/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java new file mode 100644 index 0000000000..64118e6307 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/main/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitialized.java @@ -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; + } +} diff --git a/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java new file mode 100644 index 0000000000..c4773d6442 --- /dev/null +++ b/core-java-modules/core-java-exceptions-4/src/test/java/com/baeldung/exception/variablemightnothavebeeninitialized/VariableMightNotHaveBeenInitializedUnitTest.java @@ -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); + } +}