Friday, January 3, 2014

# 7 Java Operators In Detail


Hello,

Wish you all a very Happy 2014..! :)

I believe you know how to declare a variable and its types. Now let us talk about Java operators so that we can play with the variables..!
In Java, we have many operators which make our tasks easy to accomplish. We can classify Java Operators as following,
  1. Assignment Operator
  2. Arithmetic Operators
  3. Unary Operators
  4. Equality and Relational Operators
  5. Conditional Operators
  6. Ternary Operator
  7. Type Comparison Operator
  8. Bitwise and Bitshift Operator
Let us see about each category in detail.

1. Assignment Operator
The name itself says that this operator will assign a value to variable. The right hand side value will be assigned to the left hand side variable.
= (Equal to)
Syntax:

<datatype> <variable> = <value>;
Ex:
  int a = 20;
The value 20 has been assigned to the variable “a” which is of primitive type integer.

2.Arithmetic Operators
These operators are used to perform arithmetic calculations. Following are the arithmetic operators that are supported by Java.
Arithmetic Operator
Usage
+
Used for addition and also for concatenation (joining).
-
Used for subtraction
*
Used for multiplication
/
Used for division
%
Used for getting the remainder from the division.
Syntax:
<variable 1> <arithmetic operator> <variable 2>;
Ex: 
int result = 1 + 2;  //Addition
int result = 1 - 2;  //Subtraction
int result = 1 % 2; // Get Remainder

Note:  We can also mix the arithmetic and assignment
operator to form Compound assignments. See the following examples.
int result =0;       // Initially the result value is zero
result+=5;  OR  result = result +5;   // both the statements meant same..!! result value will be 0+5=5;
same way u can also mix the other arithmetic operators and assignment operator.
result -=5;           // Subtraction
result *=10;        // Multiplication
result /=10;         // Division

result %=10;       // Reminder division
Here I want to highlight a point regarding the Compound Statements,
If we have a compound statement
i += j;
It is exactly equal to
i = (data type of i) (i + j);
Also I have mentioned that the “+” operator
can be used for concatenation. Following example will give you clear idea.
String str1 = “Hello”;
String str2 = “-LindlarsForLife”;
System.out.println(str1+str2);       // prints Hello-LindlarsForLife
String str3 = str1+str2;
System.out.println(str3);              // also prints Hello-LindlarsForLife

3. Unary Operators:
We call these operators as Unary because these operators need ONLY one operand..! Following are the unary operators.

Unary Operator
Usage
+
Indicates a positive number
-
Indicates a negative number
 ++
Increments the value by 1
--
Decrements the value by 1
!
Complements the boolean value







The increment/decrement operators (++ and --) can be applied before (prefix) and after (postfix) the operand to increase or decrease the operand value by 1.
Many people get confused about the difference between result++ and ++result.

Burn this into your head,
The prefix version (++result) evaluates to the incremented value, where as the postfix version (result++) evaluates to the original value.
                
The below example gives you more idea. Assume I have a variable “x” whose value is 6.
int x =6;
  x++;       // x value is 7
  ++x;       // x value is 7

Here both x++ and ++x produces same result. But the difference evolves when an assignment operator is involved. See this.

y = x++;       // assume initial value of x is 6. Now the value of x will be 7 and y will be 6.
y = ++x;       // assume initial value of x is 6. Now x value is 7 and y value is 7.

Initial Value of x
Code Statement
Final Value of y
Final Value of x
6
y = ++x;
7
7
6
y = x++;
6
7
6
y = --x;
5
5
6
y = x--;
6
5

Burn this rule into your head,
If the increment (or decrement) operator is followed by the operand
(e.g. ++x), then it operates before the operand takes part in the rest of the expression. On the other
hand, if the operand is followed by the operator (e.g. x++), then the operand takes part in the expression before the operator operates on it.

4. Equality and Relational Operators

The relational operators are used in an if else conditions. If you want to find the greater than or less than between two variables, you have to use these operators.

Relational Operators
Usage
==
Equal to
!=
Not equal to
 >
Greater than
>=
Greater than or equal to
!<
Less than
<=
Less than or equal to

Note:
“=” is an assignment operator where as “==” is used to find if 2 numbers are equal or not.

Syntax:

5. Conditional Operators
Java supports 2 conditional operators. These 2 operators exhibits short-circuit behavior.
Conditional Operators
Usage
&&
Conditional AND
||
Conditional OR

The “&&” (AND) behavior is explained in the following table.
A
B
A && B
TRUE
TRUE
TRUE
TRUE
FALSE
FALSE
FALSE
TRUE
FALSE
FALSE
FALSE
FALSE
 Where A and B are 2 Java operands.

The “||” (OR) behavior is explained in the following table.
A
B
A || B
TRUE
TRUE
TRUE
TRUE
FALSE
TRUE
FALSE
TRUE
TRUE
FALSE
FALSE
FALSE

Simple Rule:

  1.        && operator will be TRUE if and only if both the operators are TRUE.
  2.        || operator will be FALSE if and only if both the operators are FALSE.


The Conditional operators are also mostly used in if else conditions.

Syntax:

if(<variable1> && <variable 2>){
// condition returned true.
 }else{
// condition returned false
}

Ex:
boolean x= true;
boolean y = false;
if(x || y ){                // this condition returns true as per the || behavior.
System.out.println(“Condition is true.”)
}else{
System.out.println(“Condition is false.”)
}

6. Ternary Operator
Ternary operator helps the developers to develop code in a more readable way. It is a type of Conditional Operator. It works depend on the Boolean value of the condition. If the condition is true, then perform something. If the condition is false, then perform something else. Java supports only ONE ternary operator.
?:
See the below code,
if(a==b){
do something..
}else{
do something else
}
The entire above code can be placed in a single line with the help of ternary operator.
a==b ? doSomething : doSomethingElse;
The syntax for the ternary operator is as follows,
<expression which returns boolean> ? <execute this if expression is TRUE> : <execute this if expression is FALSE>;

7. Type Comparison Operator
Of all the Java Operators, this comparison operator is the one I love most..! :D We have only one Type Comparison Operator – intanceof
This instanceof operator is used to test if an object belongs is of specified type of a class or a subclass.

Burn this into your head à The instanceof operator will help us to downcast safely.
 We will discuss more about Upcasting and Downcasting in future posts.

8. Bitwise and Bitshift Operator
As the name suggests, these operators works with bits (0 and 1).
The Bitwise operators perform operation on each bit. Following are the Bitwise operators that are supported by Java.
Bitwise Operator
Usage
&
AND
^
XOR (Exclusive OR)
|
OR (Inclusive OR)
 ~
Complement

We have 3 Bitshift operators in Java.
Bitshift Operator
Usage
<< 
Signed Left Shift Operator
>> 
Signed Right Shift Operator
>>> 
Un-signed Right Shift Operator

“<<” will shift the bit pattern one step left.
“>>” will shift the bit pattern one step right.

“>>>” operator also shifts the bit pattern to right. But for each step, the operator will add zero to the left most bit of the pattern.

Happy Coding.! Thanks :) 

0 comments:

Post a Comment