Aug 26, 2011

Operators

Operators are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternary meaning taking one, two, or three arguments, respectively. A unary operator may appear before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.

Operators in java fall into 8 different categories:
Assignment, Arithmetic, Relational, Logical, Bitwise, Compound assignment, Conditional, and Type.
Assignment Operator
          It's very common to see statement like the following, where you're adding something to a variable. Java Variables are assigned, or given, values using one of the assignment operators. The variable are always on the left-hand side of the assignment operator and the value to be assigned is always on the right-hand side of the assignment operator. The assignment operator is evaluated from right to left, so a = b = c = 0; would assign 0 to c, then c to b then b to a.

i = i + 2;
Here we say that we are assigning i's value to the new value which is i+2.

A shortcut way to write assignments like this is to use the += operator. It's one operator symbol so don't put blanks between the + and =.
i += 2; // Same as "i = i + 2"
Examples:
     //assign 1 to variable a
       int a = 1;

     //assign the result of 2 + 2 to b
     int b = 2 + 2;

     //assign the literal "Hello" to str
      String str = new String("Hello");

     //assign b to a, then assign a to d; results in d, a, and b being equal
     int d = a = b;

Arithmetic Operators
      1.Operator (+)
         Example :
         x+y
        adds the values of x and y .

       2.Operator (++)
          Example :
          ++x or x++
         Increase the value of x by 1 .

       3.Operator (-)
          Example :
          x-y
          subtract y from x

       4.Operator (--)
          Example :
          --x or x--
         decrease the value of x by 1 .

       5.Operator (*)
          Example :
          Code:
          x*y
          multiply the value of x by y .

        6.Operator (/)
            Example :
            x/y
           divide the value x by y .

        7. Operator (%)
            Example :
            x%y
           Get the remainder of dividing x ,y 
Relational Operators
          A relational operator compares two operands to determine whether one is greater than, greater than or equal to, less than, less than or equal to the other:
         
           >    greater than
           >=   greater than or equal to
           <    less than
           <=   less than or equal to

When used in an expression they all return a boolean value which states the result of the comparison (i.e., 4 > 3 can be read as is 4 greater than 3? Which returns true).
Examples:
           int three = 3;
           int four = 4;

           //is four greater than three?
            System.out.println(four > three); //true

           //is four greater than or equal to four?
            System.out.println(four >= four); //true

           //is four less than three?
            System.out.println(four < three); //false

           //is four less than or equal to three?
            System.out.println(four <= three); //false

 Logical Operators
          Java provides an easy way to handle multiple conditions: the logic operators. There are three logic operators, &&, || and !.
&& is logical and. && combines two boolean values and returns a boolean which is true if and only if both of its operands are true. For instance
boolean b;
        b = 3 > 2 && 5 < 7; // b is true
        b = 2 > 3 && 5 < 7; // b is now false
       || is logical or. || combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true. For instance
boolean b;
       b = 3 > 2 || 5 < 7; // b is true
       b = 2 > 3 || 5 < 7; // b is still true
       b = 2 > 3 || 5 > 7; // now b is false
The last logic operator is ! which means not. It reverses the value of a boolean expression. Thus if b is true !b is false. If b is false !b is true.
boolean b;
      b = !(3 > 2); // b is false
      b = !(2 > 3); // b is true
These operators allow you to test multiple conditions more easily.
Bitwise Operators
           Java provides Bit wise operators to manipulate the contents of variables at the bit level.These variables must be of numeric data type ( char, short, int, or long).
 1. The AND operator : (&)
           Code:

               x           y                 x&y
             -----------------------------
              0           0                  0
              0           1                  0
              1           0                  0
              1           1                  1

Example :
     byte x = 50;
     byte y = 51;
     byte result = (byte) (x&y);
     System.out.println("Result of x&y= : " + result );
     Result of x&y =: 50

      00110010
      00110011
     -------------
      00110010

2-.The OR operator : (|)
             Code:

                   x           y                 x|y
                -----------------------------
                   0           0                  0
                   0           1                  1
                   1           0                  1
                   1           1                  1

Example :
            byte x = 50;
            byte y = 51;
            byte result = (byte) (x|y);
            System.out.println("Result of x|y= : " + result );
            Result of x/y =: 51

            00110010
            00110011
           -------------
            00110011

3. The XOR operator : (^)
           Code:

                  x           y                 x^y
               -----------------------------
                  0           0                  0
                  0           1                  1
                  1           0                  1
                  1           1                  0

Example :
             byte x = 50;
             byte y = 51;
             byte result = (byte) (x^y);
             System.out.println("Result of x^y=  " + result );
             Result of x^y  = 1

             00110010
             00110011
            -------------
             00000001

4.The Inversion Operator: (~)
    Invert each bit in the byte .

Example :
          ~00110010 = 11001101
Compound assignment Operators
               Compound assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.
For example, to assign the result of an addition operation to a variable:
         //add 2 to the value of number
         number = number + 2;
Using the compound assignment operator "+=" shortens the expression:
         //add 2 to the value of number
          number += 2;
There are eleven compound assignment operators:
                     +=   assigns the result of the addition.
                      -=    assigns the result of the subtraction.
                      *=    assigns the result of the multiplication
                       /=    assigns the result of the division.
                     %=    assigns the remainder of the division.
                     &=    assigns the result of the logical AND.
                       |=    assigns the result of the logical OR.
                      ^=    assigns the result of the logical XOR.
                    <<=    assigns the result of the signed left bit shift.
                    >>=    assigns the result of the signed right bit shift.
                  >>>=    assigns the result of the unsigned right bit shift.
Conditional Operators
                The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)
Example:
                   public class MainClass {
                   public static void main(String args[]) {
                   int i, k;
                   i = 10;
                   k = i < 0 ? -i : i; // get absolute value of i
                   System.out.print("Absolute value of ");
                   System.out.println(i + " is " + k);
                   i = -10;
                   k = i < 0 ? -i : i; // get absolute value of i
                   System.out.print("Absolute value of ");
                   System.out.println(i + " is " + k);
               }
             }
output:
           Absolute value of 10 is 10
           Absolute value of -10 is 10
Type  conversion
          Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur explicitly, as specified inthe program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions.
In java Conversions can occur by the following ways:
              •  Using a cast operator (explicit promotion)
              •  Using an arithmetic operator is used with arguments of different data types (arithmetic promotion)
              •   A value of one type is assigned to a variable of a different type (assignment promotion)

Operator Precedence
          The order in which operators are applied is known as precedence. Operators with a higher precedence are applied before operators with a lower precedence. The operator precedence order of Java is shown below. Operators at the top of the table are applied before operators lower down in the table. If two operators have the same precedence, they are applied in the order they appear in a statement.
That is, from left to right. You can use parentheses to override the default precedence.


postfix [] . () expr++ expr–
unary ++expr –expr +expr -expr ! ~
creation/caste new (type)expr
multiplicative * / %
additive + -
shift >> >>>
relational < <= > >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = “op=”

Example:
In an operation such as,
result = 4 + 5 * 3
First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that ‘*’ takes higher precedence than ‘+’ according to chart shown above. This kind of precedence of one operator over another applies to all the operators.

0 comments :

Post a Comment