{"record":{"id":"e2924a7ea38b8f51","repo":"TheAlgorithms/Java","slug":"input-must-contain-only-0-and-1","errorCode":null,"errorMessage":"Input must contain only '0' and '1'.","messagePattern":"Input must contain only '0' and '1'\\.","errorType":"validation","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java","lineNumber":36,"sourceCode":"public final class TwosComplement {\n    private TwosComplement() {\n    }\n\n    /**\n     * Computes the Two's Complement of the given binary string.\n     * Steps:\n     * 1. Compute the One's Complement (invert all bits).\n     * 2. Add 1 to the One's Complement to get the Two's Complement.\n     * 3. Iterate from the rightmost bit to the left, adding 1 and carrying over as needed.\n     * 4. If a carry is still present after the leftmost bit, prepend '1' to handle overflow.\n     *\n     * @param binary The binary number as a string (only '0' and '1' characters allowed).\n     * @return The two's complement of the input binary string as a new binary string.\n     * @throws IllegalArgumentException If the input contains non-binary characters.\n     */\n    public static String twosComplement(String binary) {\n        if (!binary.matches(\"[01]+\")) {\n            throw new IllegalArgumentException(\"Input must contain only '0' and '1'.\");\n        }\n\n        StringBuilder onesComplement = new StringBuilder();\n        for (char bit : binary.toCharArray()) {\n            onesComplement.append(bit == '0' ? '1' : '0');\n        }\n\n        StringBuilder twosComplement = new StringBuilder(onesComplement);\n        boolean carry = true;\n\n        for (int i = onesComplement.length() - 1; i >= 0 && carry; i--) {\n            if (onesComplement.charAt(i) == '1') {\n                twosComplement.setCharAt(i, '0');\n            } else {\n                twosComplement.setCharAt(i, '1');\n                carry = false;\n            }\n        }","sourceCodeStart":18,"sourceCodeEnd":54,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java#L18-L54","documentation":"Thrown by TwosComplement.twosComplement(String) when the input does not match the regex [01]+. The method first inverts all bits then adds 1 with carry, so it requires a pure binary string. Note: unlike OnesComplement, this method does NOT guard against null — calling it with null will throw NullPointerException on binary.matches(...) before this message is ever reached.","triggerScenarios":"Passing a string containing any non-binary character. Passing null will instead produce an NPE at the regex check, not this IllegalArgumentException.","commonSituations":"Forgetting that null is not handled (NPE rather than this error); passing binary with whitespace or a 0b prefix; mixed encodings.","solutions":["Pre-validate with regex ^[01]+$ and reject non-matching input.","Guard for null separately, since this method throws NPE (not this message) on null.","Strip whitespace and 0b prefixes before invoking."],"exampleFix":"// before\nString out = TwosComplement.twosComplement(input);\n\n// after\nif (input == null || !input.matches(\"[01]+\")) {\n    throw new IllegalArgumentException(\"Require non-null binary string\");\n}\nString out = TwosComplement.twosComplement(input);","handlingStrategy":"validation","validationCode":"if (binary == null || !binary.matches(\"[01]+\")) {\n    throw new IllegalArgumentException(\"Require a non-null [01]+ string\");\n}\nString out = TwosComplement.twosComplement(binary);","typeGuard":"static boolean isValidForTwos(String s) { return s != null && s.matches(\"[01]+\"); }","tryCatchPattern":"try {\n    String out = TwosComplement.twosComplement(binary);\n} catch (IllegalArgumentException | NullPointerException e) {\n    // note: null throws NPE here, not IAE\n}","preventionTips":["Remember this method does NOT null-guard — check null yourself to avoid NPE.","Validate contents with [01]+ before calling.","Strip formatting/whitespace upstream."],"tags":["bit-manipulation","java","validation","string","null-safety","illegalargumentexception"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}