Java Bitwise Complement

Java Bitwise Complement Operator is used to perform complement operation for a given operand. Complement Operator takes only one operand, and that is on right side.

Syntax

The syntax for Bitwise Complement operation for x is

~x

The operand can be of type int or char. Bitwise Complement operator returns a value of type same as that of the given operands.

The following table illustrates the output of Complement operation between two bits.

bit~bit
01
10
ADVERTISEMENT

Examples

In the following example, we take an integer value in x, and find the bitwise complement of x.

Main.java

public class Main {
    public static void main(String[] args) {
        int x = 5;
        //Bitwise Complement
        int result = ~ x;
        System.out.println("Result : " + result);
    }
}

Output

Result : -6

In the following example, we take a char value in x, and find the bitwise complement of x.

main.cpp

public class Main {
    public static void main(String[] args) {
        char x = 'a';
        //Bitwise Complement
        int result = ~x;
        System.out.println("Result : " + result);
    }
}

Output

Result : -98

Conclusion

In this Java Tutorial, we learned what Bitwise Complement Operator is, it’s syntax, and how to use this operator in Java programs, with the help of examples.