Operators in java



A programmer need generally wants to do some operations in a program. For example, in a program you want to perform multiplication of two numbers. Here we use * symbol for multiplication. The symbols like +,-,* are called operators and programming becomes easy because of them.
An operator acts on some variables  called operands to get the desired results. If an operator acts on a single variable it is called unary operator. If it is acting on two variables then it is called binary operator. If three, then it is called ternary operator.
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:
1.  Arithmetic Operators
2.  Relational Operators
3.  Bitwise Operators
4.  Logical Operators
5.  Assignment Operators
6.  Misc Operators
Arithmetic operators:  these are used in mathematical expressions in the same way that they are used in algebra.  There are 5 arithmetic operators in java.
The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Operator
                           Description
Example                                                          
+
  Addition - Adds values on either side of the operator
  A + B will give 30
-
  Subtraction - Subtracts right hand operand from left hand operand
  A - B will give -10
*
  Multiplication - Multiplies values on either side of the operator
 A * B will give 200
/
  Division - Divides left hand operand by right hand operand                              
B / A will give 2
%
Modulus - Divides left hand operand by right hand operand and returns remainder 
B % A  give 0
Additional operator (+) is also    used to join two strings.
Ex:  String s1=”teach”; String s2=”you well”;
               String s3=s1+s2;            //here + joins s1 and s2.
Here + is called string concatenation operator.
Unary Operators
As the name indicates, unary operators act on only one operand. There are 3 kinds of unary operators:
1. Unary minus operator ( -)
2. Increment operator ( ++)
3. Decrement operator ( --)
Unary Minus Operator (-)
This operator is used to negate a given value. Negation means converting a negative value
into positive and vice versa. For example:
 int x=20;
System.out.println(-x); //will display -20
System.out.println(-(-x)); //will display 20

Increment Operator (++)
This operator increases the value of a variable by 1 for example:
int x=1;
System.out.println(++x); //will display 2
System.out.println(x++); //will display 3

Here, the value of the variable x is incremented by 1 when  ++ operator is used before or after it.
Both are valid expressions in Java. Let us take an example to understand It better
Writing ++ before a variable is called pre incrcmentation and writing ++ after a variable is called post
Incrementation.  In pre incrementation,   incrernentation is done first and any other operation  is done
next.  In post incrementation,  all the other operations are done first and incrementation is done only
at the end. To understand the difference between pre and post incrementation, let us take a couple
of examples.

Ex1:
int x=1;
System.out.println(x);  //displays 1
System.out.println(++x); //will display 2
System.out.println(x); //will display 3


Ex2:
int x=1;
System.out.println(x);  //displays 1
System.out.println(x++); //will display 1
System.out.println(x); //will display 2

In this example, see the left-hand side and right-hand side statements. The second statement on
the left uses pre-incrementation.  while the second statement on the right uses post-incrementation.
At the left hand side:
Syat.m.out.println(x);      // displays the value of x as 1
 System.out.printlnt(++x); // first increments the value of x and then displays it as 2
 System.out.println(x);    // displays the value of x, which  is already incremented i.e. 2
At the right hand side:
 System.out.println(x);      // It displays the value of x, i.e. 1
System.out.prtntln(x++);   // first displays the value of x as 1 and then increments it.
 Systam.out.println(z);       // displays the incremented value of x, i.e. 2

Decrement Operator (--)
This operator is used to decrement the value of a variable by 1.
Ex:
Int x=1;
System.out.println(--x);      // It displays the value of x as 0
System.out.prtntln(x--);   // it displays the value of x as -1

This means, the value of x is decremented every time we use  --  operator on it. This is same as
writing  x= x-1.
Writing -- before a variable is called pre-decreinentation and writing - - after a variable is called
post - decrementation. Like the incrementation operator, here also the same rules apply.
 Pre-decrementation is done immediately then and there itself and Post-decrementation is done after
 all the other operations are carried out.

Relational Operators:
These operators are used for the purpose of comparing. The main use of these operators is in the construction of conditions in statements.
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20 then:
Operator
Description
Example
==
Checks if the value of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
!=
Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.
(A != B) is true.
Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
(A > B) is not true.
Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
(A >= B) is not true.
<=
Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.
(A <= B) is true.


Bitwise Operators:
There are 7 types of bitwise operators in java.  which can be applied to the integer types, long, int, short, char, and byte.  These operators operate on individual bits of integer (int and long) values. If an operand is shorter than an int, it is promoted to int before doing the operations.
It helps to know how integers are represented in binary.  Binary number system uses only  2 digits. They are 0 and 1.   For example the decimal number 3 is represented as 11 in binary and the decimal number 5 is represented as 101 in binary. Negative integers are store in two's complement form. For example, -4 is 1111 1111 1111 1111 1111 1111 1111 1100.

Operator
Name
Description
 &
and
Binary AND Operator copies a bit to the result if it exists in both operands.
 |
or
Binary OR Operator copies a bit if it exists in either operand.
 ^
xor
Binary XOR Operator copies the bit if it is set in one operand but not both.
 ~
not
Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.
 <<
left shift
Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.
 >>
right shift
Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.
 >>>
right shift
Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

Example:  let us assume a=10,b=11.
a = 0000 1010
b = 0000 1011

a&b = 0000 1010
a|b = 0000 1011
a^b = 0000 0001
~a  = 1111 0101
a<<2 = 0010 1000
a>>2 = 0000 0010

Logical operators:
Logical operators are used to construct compound conditions. A compound condition is a combination of several simple conditions. The following are the logical operators.
1.       &&  (and) operator
2.       ||  (or) operator
3.       !  not operator
Let us assume X and Y are Boolean variables and X holds true , Y holds false.
Operator
Description
Example
  &&
Called Logical AND operator. If both the operands are non zero then  condition becomes true.
(X && Y) is false.
    ||
Called Logical OR Operator. If any of the two operands are non zero then  condition becomes true.
(X || Y) is true.
    !
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(X && Y) is true.

Boolean operators:
These Boolean operators are act on Boolean variables and gives Boolean type results. The following are the Boolean operators.
1.       &boolean  and operator
2.       |boolean  or operator
3.       !boolean not operator
Boolean & operator return true  if both the variables are true.
Boolean | operator return true if any one of the variable is true.
Boolean ! operator coverts  false true and vice versa.
Example:
boolean x,y;
x=true;
y=false;
x & Y       //returns false and gives true only if both are true
x | Y       //returns true
a & a     //returns true because both are true
b | b      //returns false since both are false
!a           //returns false
!b          //returns true

Assignment Operator (=)
This operator is used to store some value into a variable, It is used In 3 ways:
1. It Is used to store a value into a variable, for example:  int  x =1 5;
2. It Is used to store the value of a variable into another variable, for example: int a=b;
3. It is used to store the value of an expression into a variable, for example:
     int  a = b-c+5; //here a-b+5 is evaluated and its result is stored into x.

We cannot   use more than one variable at the left hand side of the = operator
 For example:  a+b = 10; // this is invalid

We cannot use a literal  or constant value at the left side of the operator.
 For example: 10 = a;

Compact Notation
While using assignment operator (=), sometimes we may have to use same variable at both
sides of the operator. In such cases, we can eliminate repetition of the variable and use compact
notation or short cut notation. As like as below

Operator
Description
Example
=
Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C
+=
Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
C %= A is equivalent to C = C % A
<<=
Left shift AND assignment operator
C <<= 2 is same as C = C << 2
>>=
Right shift AND assignment operator
C >>= 2 is same as C = C >> 2
&=
Bitwise AND assignment operator
C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and assignment operator
C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and assignment operator
C |= 2 is same as C = C | 2
Experienced programmers use compact notations. However, both the expanded and compact
notation,  are valid in Java.
Misc Operators:
Java supports  a few operators. They are ternaray operator, member operator, new operator,  instance of operator, cast operator.
Ternary operator or conditional operator (?:)
This operator is called ternary because it acts on 3 variables. The other name for this operator is conditional operator, since it represents a conditional statement. Two symbols are used for this operator ? and :

Syntax is variable = expression1 ? expression2 : expression3;

This means that first of all, expression1 is evaluated. If it is true, then expression2 value is stored into the variable. If expression1 is false, then expression3 value is stored into the variable.

If(expression1 is true)
  Variable = expression2
Else variable = expression3;

Ex:
public class Test {

   public static void main(String args[]){
      int x , y;
      x = 10;
      y = (x == 1) ? 20: 30;
      System.out.println( "Value of y is : " +  y );

      y = (x == 10) ? 20: 30;
      System.out.println( "Value of y is : " + y );
   }
}
 Output:
Value of y is : 30
Value of y is : 20

Member operator (.)
This is also called dot operator because its symbol is a . (dot or period). This operator tells about member of a package or a class. It is used in three ways:
1.       Java package contains classes. We can use . operator to refer to the class of a package.
Syntax:  packagename.classname;
2.       We know each class contains variables. To refer to the variables of a class, we can use this operator.
Syntax: classname.variablename;    objectname.variablename;
3.       We know each class contains methods. To refer to the methods of a class, we can use this operator.
Syntax: classname.methodname;  objectname.methodname;
instanceof operator:
This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type). instanceOf operator is wriiten as:
Syntax:  boolean variable = object instance of class;
               boolean  variable = object instance of interface;
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side then the result will be true.

 Following is the example:
String name = ‘teachuwell’;
boolean result = name instanceOf String; 
// This will return true since name is type of String

This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:

class Vehicle {}
public class Car extends Vehicle {
   public static void main(String args[]){
      Vehicle a = new Car();
      boolean result =  a instanceof Car;
      System.out.println( result);
   }
}
Output:true

new operator:
This operator generally used for creating object to classes.
Syntax:  classname object = new classname();
Ex:  Vehical veh = new Vehical();  //veh is an object of Vehical class

Cast operator:
Cast operator is used to convert one datatype into another datatype. This operator can be used by writing datatype inside simple braces.
Ex: double a = 5.5;
       int b = a;  // error because the datatypes of a and b are different.
To store a value into b, first we have to convert the datatype of a into the datatype of b. that means  double datatype should be converted into int datatype by writing the int inside simple braces like below.

int b = (int) a;

here (int) is called as cast operator. This is generally used before a variable or  a method.

No comments:

Post a Comment

Genuine websites to earn money.

If you are interested in PTC sites then this article is for you. I have personally tried many of the sites and found that the best thing ...