Home

Java: Negation, Bitwise Not, and Boolean Not

|
|  Updated:  
2016-03-26 12:48:55
|   From The Book:  
No items found.
Java and XML For Dummies
Explore Book
Buy On Amazon

There are two types of unary operations in Java that you should view together so that you don’t misunderstand them later on. Negation is the act of setting a value to its negative version — the value of 2 becomes –2.

Some math-related tasks require that you negate a value in order to use it. In some cases, people confuse negation with subtraction, but subtraction is a binary operation and negation is a unary operation.

Negation is the act of setting a value to its negative equivalent. A value of 2 becomes –2.

Contrast negation with the bitwise Not operation, which you implement by using the ~ operator. The Not operation reverses each of the bits in a value. All of the 0s become 1s and vice versa. The Not operation is often used in Boolean-related tasks. It helps an application consider the logic of a task.

The term bitwise means to perform a task a single bit at a time, rather than using the entire value. So, a bitwise Not operation looks at each bit individually — any 1 becomes a 0, and vice versa. Consequently, when you have a value of 5, which in binary is 00000101, it becomes a negative six, which in binary is 11111010. Notice how the bits are precisely reversed in value.

To make things even more confusing, there’s a second Not operation called a Boolean Not operation that works on Boolean values. This operation relies on the ! operator. The bitwise operator (~) won’t work on Boolean values and the logical operator (!) won’t work on values other than Boolean.

Boolean values are either true or false. When you Not a Boolean value, you turn it from true to false, or from false to true.

About This Article

This article is from the book: 

No items found.

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.