Why test your own code
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Passing the two sample inputs in a problem description only proves that your code does not crash on friendly data. Online judges and production systems run dozens of hidden tests specifically chosen to break unguarded assumptions.
Why sample tests give a false sense of security
A test case is one input with its expected output, used to check that a program gives the right answer.
A sample test only explains the problem; a hidden test suite is what the judge runs after you submit. The code below passes the sample but fails three hidden cases.
Beginners often write code, run it against the single sample in the prompt, see the matching answer, and submit immediately. Seconds later the judge returns Wrong Answer on test 14 or Runtime Error on test 27 without showing the input that failed.
Example 1 · A method that passes the sample test but fails three hidden edge cases
import java.util.Arrays;
public class SampleTrapDemo { // Buggy method: initializes max to 0 and stops at length - 1 static int buggyMax(int[] nums) { int max = 0; for (int i = 0; i < nums.length - 1; i++) { if (nums[i] > max) { max = nums[i]; } } return max; }
static int correctMax(int[] nums) { int max = nums[0]; for (int i = 1; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; } } return max; }
public static void main(String[] args) { int[][] testInputs = { {3, 9, 4, 2}, // Sample case: max is in the middle and positive {3, 4, 2, 12}, // Edge 1: max is at the last index {-8, -3, -10}, // Edge 2: all numbers are negative {-5} // Edge 3: single negative element };
for (int[] input : testInputs) { int expected = correctMax(input); int actual = buggyMax(input); String verdict = (actual == expected) ? "PASS" : "FAIL"; System.out.println(Arrays.toString(input) + " -> expected=" + expected + ", buggy=" + actual + " [" + verdict + "]"); } }}[3, 9, 4, 2] -> expected=9, buggy=9 [PASS] [3, 4, 2, 12] -> expected=12, buggy=4 [FAIL] [-8, -3, -10] -> expected=-3, buggy=0 [FAIL] [-5] -> expected=-5, buggy=0 [FAIL]
What this code does
buggyMaxhas two classic mistakes (max = 0andi < nums.length - 1), yet it still passes[3, 9, 4, 2]because9is positive and not at the last index.- As soon as we test the last-index boundary (
[3, 4, 2, 12]) and negative values ([-8, -3, -10]), both bugs are exposed immediately.
When you open a coding challenge or interview platform, the prompt usually shows one or two sample inputs. Those samples exist to clarify what the problem asks, not to prove your solution is right. A hidden test suite is the private set of inputs an online judge or automated grading pipeline runs after you click Submit.
In a live technical interview, there may not even be a Run button. The interviewer watches whether you test your own logic with well-chosen inputs before declaring "I'm done."
- Sample tests explain the input/output format using small, polite numbers.
- Hidden edge tests probe minimum lengths, negative values, duplicates, and zeroes.
- Hidden stress tests feed maximum-sized arrays (n = 10⁵) and extreme values (
Integer.MAX_VALUE) to trigger timeouts or overflow.
The three buckets of test cases: normal, edge, and large
To catch bugs before a judge does, group your test cases into three clear buckets. A normal case (also called a happy-path case) is an everyday input with several elements and no extreme values, such as [3, 7, 2, 9, 5].
Example 2 · A 3-line large test case that catches 32-bit integer overflow
import java.util.Arrays;
public class LargeCaseOverflowDemo { static int buggySum(int[] prices) { int total = 0; for (int p : prices) { total += p; } return total; }
static long safeSum(int[] prices) { long total = 0L; for (int p : prices) { total += p; } return total; }
public static void main(String[] args) { // Constraint says: 1 <= n <= 100_000, each price up to 100_000 int[] largeInput = new int[100_000]; Arrays.fill(largeInput, 100_000);
long expected = 10_000_000_000L; // 100,000 * 100,000 = 10^10 System.out.println("Small sample [10, 20, 30] buggySum: " + buggySum(new int[]{10, 20, 30})); System.out.println("Large case expected : " + expected); System.out.println("Large case buggySum : " + buggySum(largeInput)); System.out.println("Large case safeSum : " + safeSum(largeInput)); }}Small sample [10, 20, 30] buggySum: 60 Large case expected : 10000000000 Large case buggySum : 1410065408 Large case safeSum : 10000000000
What this code does
- You do not need to type 100,000 numbers into your file to test large constraints —
Arrays.fill(largeInput, 100_000)builds a worst-case input in two lines. - While
[10, 20, 30]passes both methods, the large case immediately showsbuggySumoverflowing 32-bitint(2,147,483,647) into1410065408.
- Write 1–2 normal cases to confirm the core logic works on typical inputs.
- Check the minimum size allowed by the constraints (
n = 0,n = 1, orn = 2). - Check value extremes: negatives, zeroes, duplicates, and
Integer.MAX_VALUE. - Check position boundaries: answer at the very first index, very last index, or not present at all.
- Generate a large case in code to catch
intoverflow and slow O(n²) loops.
An edge case sits at the boundary of the problem constraints where loops, conditions, or array indexes often misbehave. Common edge cases include the smallest allowed array (n = 0 or n = 1), all identical numbers ([4, 4, 4]), all negative numbers ([-8, -3, -10]), already sorted or reverse-sorted arrays, and the target value sitting at index 0 or index n - 1. A large case tests both speed and arithmetic limits. Even if you do not type 100,000 numbers by hand, you can generate an array of size 100,000 filled with 10⁹ in two lines of Java to verify that your variables do not overflow int and your loop finishes in milliseconds.
Writing the expected output first (the test table)
If you write your code first and then invent a test input by reading your own for loop, your brain will unconsciously follow the code's steps and agree with whatever output the buggy code produces. This trap is called confirmation bias.
Example 3 · Turning a test table into runnable checks in main
import java.util.Arrays;
public class TestTableDemo { // Returns the index of target, or -1 if not found static int findFirstIndex(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { if (nums[i] == target) { return i; } } return -1; }
static void check(String reason, int[] nums, int target, int expected) { int actual = findFirstIndex(nums, target); String status = (actual == expected) ? "PASS" : "FAIL"; System.out.println(status + " | " + reason + " | input=" + Arrays.toString(nums) + ", target=" + target + " | expected=" + expected + ", actual=" + actual); }
public static void main(String[] args) { check("Normal middle match", new int[]{10, 20, 30, 40}, 30, 2); check("First element match", new int[]{10, 20, 30, 40}, 10, 0); check("Last element match", new int[]{10, 20, 30, 40}, 40, 3); check("Duplicate returns first", new int[]{5, 7, 7, 7}, 7, 1); check("Target not present", new int[]{10, 20, 30}, 99, -1); check("Empty array", new int[]{}, 10, -1); }}PASS | Normal middle match | input=[10, 20, 30, 40], target=30 | expected=2, actual=2 PASS | First element match | input=[10, 20, 30, 40], target=10 | expected=0, actual=0 PASS | Last element match | input=[10, 20, 30, 40], target=40 | expected=3, actual=3 PASS | Duplicate returns first | input=[5, 7, 7, 7], target=7 | expected=1, actual=1 PASS | Target not present | input=[10, 20, 30], target=99 | expected=-1, actual=-1 PASS | Empty array | input=[], target=10 | expected=-1, actual=-1
What this code does
- Each
check(...)call represents one row of a test table: why the case exists, the input, and the expected output worked out beforehand. - Covering the first element, last element, duplicate values, missing target, and empty array leaves almost nowhere for an off-by-one bug to hide.
The cure is to build a test table before you write the method body. A test table is a short list of (input, expectedOutput, reason) rows worked out by hand from the problem statement alone. Once you have 5 to 7 rows with hand-verified expected outputs, your test cases act as an independent referee. If your code prints 0 on [-5, -2, -9] when your test table says the maximum is -2, you spot the max = 0 initialisation bug in seconds.
Next step
Check your understanding
10 quick questions