Using operators - 2
Increment and decrement operators
Two shortcut arithmetic operators are ++, which increments its operand by 1, and --, which decrements its operand by 1.
- ++ increment operator (increments value by 1)
- -- decrement operator (decrements value by 1)
These operators can appear before the operand (prefix) or after the operand (postfix). In the case of the prefix style, the value of the operand is evaluated after the increment/decrement operation. For postfix, the value of the operand is evaluated before the increment/decrement operation, as shown below:
Prefix (operator is placed before the operand):
int i = 10;
int j = ++i; // j and i are 11
System.out.println(--i); // prints 10
Postfix (operator is placed after the operand):
int i = 10;
int j = i++; // j is 10, i becomes 11
System.out.println(i--); // prints 11
Shift operators
Shift operators shift the bits of a number to the right or left, thus producing a new number:
- >> right shift (fills the left bit with whatever value the original sign bit held)
- << left shift (fills the right bit with zeros)
- >>> unsigned right shift (fills the left bits with zeros)
For instance:
8 >> 1;
Before shifting: 0000 0000 0000 0000 0000 0000 0000 1000
After shifting: 0000 0000 0000 0000 0000 0000 0000 0100
Note that decimal equivalent of the shifted bit pattern is 4.
Bitwise operators
Java provides four operators to perform bitwise functions on their operands:
- The & operator sets a bit to 1 if both operand's bits are 1.
- The ^ operator sets a bit to 1 if only one operand's bit is 1.
- The | operator sets a bit to 1 if at least one operand's bit is 1.
- The ~ operator reverses the value of every bit in the operand.
For instance:
class Test
{
public static void main(String args[])
{
int x = 10 & 9; // 1010 and 1001
System.out.println(x);
} // prints 8, which is the decimal equivalent of 1000
}
The bitwise operators & and | can be used in boolean expressions also.
Logical operators
The four logical operators are &, &&, |, and ||.
If both operands are true, then the & and && operators return true.
If at least one operand is true, then the | and || operators return true.
The & and | operators always evaluate both operands. && and || are called short circuit operators because if the result of the boolean expression can be determined from the left operand, the right operand is not evaluated. For instance:
if ((++x > 2) || (++y > 2)) { x++; }
// y is incremented only if (++x > 2) is false
Note that || and && can be used only in logical expressions.
1 comment: