Friday, January 15, 2016

Topic 8: Operators in Java

Arithmetic Operators

  • Arithmetic operators are used in mathematical expressions. The following lists the arithmetic operators: 

  • + Addition 

  • – Subtraction (also unary minus)

  • * Multiplication

  • / Division

  • % Modulus

  • ++ Increment

  • – – Decrement


  • Compound assignment operator

  •  += Addition assignment

  • –= Subtraction assignment

  • *= Multiplication assignment

  • /= Division assignment

  • %= Modulus assignment


  • The operands of the arithmetic operators must be of a numeric type or char types but not boolean.
  • The minus operator also has a unary form that negates its single operand.
  • The division operator results in int with no fractional component attached to the result.
  • The compound assignment operators are implemented more efficiently by the Java run-time system than their equivalent long forms.
 
The Bitwise Operators

 
  • Bitwise operators can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands. The following lists the operators:
  • ~ Bitwise unary NOT //Also called the bitwise complement
  • & Bitwise AND
  • | Bitwise OR
  • ^ Bitwise exclusive OR
  • >> Shift right
  • >>> Shift right zero fill
  • << Shift left
  • &= Bitwise AND assignment
  • |= Bitwise OR assignment
  • ^= Bitwise exclusive OR assignment
  • >>= Shift right assignment
  • >>>= Shift right zero fill assignment
  • <<= Shift left assignment
  • Java uses an encoding known as two’s complement, which means that negative numbers are represented by inverting (changing 1’s to 0’s and vice versa) all of the bits in a value, then adding 1 to the result. For ex, –42 is represented by inverting all of the bits in 42, or 00101010, which yields 11010101, then adding 1, which results in 11010110, or –42. To decode a negative number, first invert all of the bits, then add 1. For example, –42, or 11010110 inverted, yields 00101001, or 41, so when you add 1 you get 42.
  • The Bitwise XOR - The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1 else zero. For ex,
   00101010 //42  
^ 00001111 //15
Results is: 00100101 //37
  • The Left Shift - The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times. It has this general form: value << num
  • For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on the right. For int operand, bits are lost once they are shifted past bit position 31 and for long, after bit position 63.

  • Since byte and short values are promoted to int, the outcome of a left shift on a byte or short value will be an int, and the bits shifted left will not be lost until they shift past bit position 31. Furthermore, a negative byte or short value will be sign-extended when it is promoted to int. Thus, the high-order bits will be filled with 1’s. The easiest way to discard the high order bits and get the resultant byte or short value is to simply cast the result back into a byte or short.

  • Left shift can be used as an alternative to multiplying by 2.

  • The Right Shift - The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its general form is shown here:  value >> num

  • When a value has bits that are “shifted off,” those bits are lost. For example, the next code fragment shifts the value 35 to the right two positions, which causes the two low-order bits to be lost, resulting again in a being set to 8.


int a = 35;  //00100011

a = a >> 2; // a contains 8 after this operation//00001000
 

  • Right shift divides the value by 2 and discards any remainder.
     

  • When we shift right, the top (leftmost) bits exposed by the right shift are filled in with the previous top bit. This is called sign extension and serves to preserve the sign of negative numbers when we shift them right. For ex, –8 >> 1 is –4.

  • The Unsigned Right Shift - If, unlike >> operator which fills previous top bit, we want to shift a zero into the high-order bit no matter what its initial value was, we can use unsigned shift-right operator, >>>. The following code fragment demonstrates the >>>:

int a = -1; // 11111111 11111111 11111111 11111111

a = a >>> 24; // 00000000 00000000 00000000 11111111

Relational Operators


  • The relational operators determine equality and ordering between its operands. The outcome is a boolean value. The relational operators are shown here:

  • == Equal to  

  • != Not equal to  

  • > Greater than  

  • < Less than  

  • >= Greater than or equal to  

  • <= Less than or equal to

  • Sample code snippet:

int done;

//if(!done) ... // Valid in C/C++ but not in Java

//if(done) ... // Valid in C/C++ but not in Java

//In Java, these statements must be written like this:

if(done == 0) ... // This is Java-style.  

if(done != 0) ...

The reason is in Java, true and false are nonnumeric values and not 1 and 0 as in C/C++.

Boolean Logical Operators




  • The Boolean logical operators operate only on boolean operands with boolean result value.

  • & Logical AND

  • | Logical OR

  • ^ Logical XOR (exclusive OR)

  • || Short-circuit OR

  • && Short-circuit AND

  • ! unary NOT

  • &= AND assignment

  • |= OR assignment

  • ^= XOR assignment

  • == Equal to

  • != Not equal to 

  • ?: Ternary if-then-else

  • Given A and B, the short-circuit OR operator results in true when A is true, no matter what B is. Similarly, the short-circuit AND operator results in false when A is false, no matter what B is. If we use the || and && forms, Java will not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand alone. For ex, the following code fragment uses short-circuit logical evaluation for division:

if (denom != 0 && num / denom > 10)

  • Though useful, there are exceptions when short-circuit logical operators should not be used. For ex, consider the following statement:
if(c==1 & e++ < 100) d = 100;
Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.
  • Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements. This operator is the ?. The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the expression evaluated. Both expression2 and expression3 are required to return the same type, which can’t be void. Here is an example of the way that the ? is employed:

ratio = denom == 0 ? 0 : num / denom;

The Assignment Operator




  • The assignment operator is the single equal sign, =. It has this general form: 

var = expression;

Here, the type of var must be compatible with the type of expression.

  • The assignment operator can create a chain of assignments. For example, consider this fragment:

int x, y, z;

x = y = z = 100; // set x, y, and z to 100

This fragment sets the variables x, y, and z to 100 using a single statement. This works because the = is an operator that yields the value of the right-hand expression. Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x. 

Operator Precedence




  • Operators below are arranged in the order of highest to lowest precedence. Operators with equal precedence are defined on the same line:

(), [], .

++, --, ~, !

*, /, %

+, -

>>, >>>, <<

>, >=, <, <=

==, !=

&

^

|

&&

||

?:

=, op=


 Additional use of + operator


  • Apart from using + operator to add two numbers, we can use + in print or println statements to combine many items together. 



Important note: Parentheses (redundant or not) do not degrade the performance of our program. Therefore, adding parentheses to reduce ambiguity does not negatively affect your program.




Click for NEXT article.

 

Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment