Operators in Java |

## Operators in Java:

An operator takes one or more arguments and produces a new value. The arguments are in little different from ordinary method calls but results the same. All operators produces a value from their operand. An operator can change the value of an operand. This is called a side effect.The most common use for operators that modify their operand is to generate the side effect.But the value produced is available for our use as in operators without side effect.### There are the below types of operators available in java

- Arithmetic operator
- Concatenation operator
- Assignment operator
- Unary operator
- Relational operator
- Ternary operator
- Conditional operator
- Type comparison operator
- Bitwise operator
- Shift operator
- Other Operator

###

**Arithmetic Operator**

####
**Mixed Mode Arithmetic**

```
=20/10 //will produce 2 and
=20/10.0 // will produce 2.0
```

Operator | Expression | Example | Comment |
---|---|---|---|

Addition | + | a+b | For numerical values it is addition |

Substraction | - | a-b | Subtracts right from left |

Multiplication | * | a*b | multiplies left with right |

Divition | / | a/b | |

Modulas | % | a%b | applicable for integer data |

###
**Concatenation operator:**

```
public class MyStringTest{
public static void main(String []args){
int i=1;
int j=2;
int k=3;
String myString="i j k ";
System.out.println(myString+i+j+k);
System.out.println(i+j+k+myString);
}
}
```

Output of the code:$javac MyStringTest.java

$java -Xmx128M -Xms16M MyStringTest

i j k 123

6 i j k

As the expression begins with String compiler will convert i,j,k into String and concatenate instead of addition.

Operator | Expression | Example | Comment |
---|---|---|---|

Concatenation | + | "Java"+" "+"Love" | String context it is concatenation |

###
**Assignment operator**

- Direct assignment
- Shorthand assignment

Operator | Expression | Example | Comment |
---|---|---|---|

assignment | = | c=a+b | assigns the result to the left |

subtract AND | -= | a-=b | it is equivalent to a=a-b |

add AND | += | a+=b | it is equivalent to a=a+b |

divide AND | /= | a/=b | it is equivalent to a=a/b |

multiply AND | *= | a*=b | it is equivalent to a=a*b |

####
**Advantages:**

- What appears on the left hand side need not be repeated and therefore it becomes easier to write.
- The statement is more concise and easier to read.
- This results a more efficient code.

###
**Unary operator**

```
x=-a;
x=a*-b;
x=a*(-b);
```

Operator | Expression | Example | Comment |
---|---|---|---|

unary plus | + | Indicates positive values | |

unary minus | - | negates an expression | |

increment | ++ | a++ | Increments the value by one |

decrement | -- | a-- | decrement the value by one |

- pre increment and post increment
- pre decrement and post decrement

```
int i=1;
++i;//(i=2) pre increment and then assignment
i++;(i=2 first assignment and then increment)
//final value i=1
//similarly
--i;(i=2 predecrement and assignment)
i--;(i=2 assignment and then decrement)
//final value i=1
```

###
**Relational operator**

Operator | Expression | Example | Comment |
---|---|---|---|

not | ! | !a | logical compliment operator inverts the value of a returns boolean |

equals | == | a==b | checks equality, returns boolean |

not equal to | != | a!=b | checks if a is not equal to b, returns boolean |

greater than | > | a>b | checks if a is greater than b, returns boolean |

less than | < | a<b | checks if a is less than b returns boolean |

greater than equal to | >= | a>=b | checks if a is greater than or equals to b, returns boolean |

less than equal to | <= | a<=b | checks if a is less than or equals to b, returns boolean |

```
a+b==c+d //is true if both side are equal.
```

Relatational operators are used in decision statements such as if,while etc to decide the next course of action.#### Compound Operator:

++ and -- are called compound operator and can not have space in between.

###
**Conditional operator or Logical Operator:**

Operator | Expression | Example | Comment |
---|---|---|---|

conditional AND | && | a&&b | |

conditional OR | || | a||b |

###
**Short circuiting:**

Short circuiting means that the expression will be evaluated until the truth or falsehood of the entire expression can be unambiguously determined.As a result all the parts of a logical expression may not get evaluated.Like-```
if(test1()&&test2()&&test3())
```

In this example if test1() function returns true,control will try to execute test2() function,if test2() returns true then test3() will be executed. Now if any of these function generate a false output,the whole expression becomes false,irrespective of the yield of the other functions.Java will not carry out the execution of the other function if it detects any false statement or false yield from any of the functions while going from left to right.This leads to potential performance increase if all the parts of the logical expression do not need to be executed.They follow the below truth table:

Operator -1 | Operator-2 | Operator1&&operator2 | Operator1||operator2 |
---|---|---|---|

true | true | true | true |

true | false | false | true |

false | true | false | true |

false | false | false | false |

###
**Ternary operator**

**?:**.This operator is unusual because of only three operands.Since it produces a value it is truly an operator.

the generic syntax:

```
x=(expession1)?(expession2):expession3
//it is equivalent to
if(expession1){
x=expession2;
}
else{
x=expession3;
}
```

The logic is if expession1 is evaluated and it is true then the expession2 is evaluated and the operator produces expession2 value .If it is false the then expession3 is evaluated and the operator produces expession3 value.It is very much distinct from if else .It is more compact as well.But it is less easier to understand.:(```
public class MyTernaryTest{
public static void main(String []args){
for(int i=1;i<100;i=i+10)
{
System.out.println("The value of i "+i+" "+myTernary(i));
}
}
private static int myTernary(int i)
{
return i<10?i*100:i*10;
}
}
```

The output of the code:$javac MyTernaryTest.java

$java -Xmx128M -Xms16M MyTernaryTest

The value of i 1 100

The value of i 11 110

The value of i 21 210

The value of i 31 310

The value of i 41 410

The value of i 51 510

The value of i 61 610

The value of i 71 710

The value of i 81 810

The value of i 91 910

###
**Type comparison operator**

```
if(student instanceOf Student)
{
}
else
{
}
//or Triangle instanceOf Shape
```

they return true if student is an instance of Student or Triangle is an instance of Shape.###
**Bitwise operator**

Bitwise AND operator(&) produces a one in the output bit if both input bits are one,otherwise it produces zero.

Bitwise OR operator(|) produces a one in the output bit one of the input bits is one,it produces zero if both are zero.

Bitwise Exclusive OR or XOR operator(|) produces a one in the output if one or the other input bit is one,but not both.

Bitwise NOT(~) or complement operator is unary operator. It only takes one argument(all other bitwise operator are binary operator).It produces the opposite of the input bit.A one if the input bit is zero and a zero if the input bit is one.

Bitwise operators and logical operators uses same character as bits are small. There is only one character in the bitwise operator.

Bitwise operators can be combined with =,&=,|=,^=. ~ is an unary operator and can not be combined with = sign.

The boolean type is treated as an one bit value so it is somewhat different.We can perform a bitwise AND,OR,XOR but can not perform NOT.

###
**Shift operator**

The signed right shift operator(>>) produces the operand to the left of the operator shifted to right by the number of bits specified after the operator.The signed right shift (>>) uses sign extension.If the value is positive,zeros are inserted at the higher order bits.If the value is negative,ones are inserted at the higher order bits.

Java also has added unsigned right shift(>>>) which uses zero extension,regardless of the sign,zeros are inserted at the higher order bits.If we shift a char,byte or short, it will be promoted to int before the shift operation takes place.The result will be in int.Only the five order bits of the right hand side will be used.This prevents shifting more than the number of bits in an int.If we are operating on long,long will be the result.Only six low order bits of the right hand side will be used.This prevents us from shifting more than the number of bits in an int.

Shifts can be combined with equal sign like-<<=,>= or >>>=.The value is replaced by the lvalue shifted by rvalue.

```
static void bitInt(String s,int i)
{
System.out.println(s+",int:"+i+",binary:");
System.out.println(" ");
for(int j=31;j>=0;j--)
if(((1<<j)&j>!=0)
System.out.println("1");
else
System.out.println("0");
}
```

Operator | Expression | Example | Comment |
---|---|---|---|

left shift | << | <<a | |

right shift | >> | a>> | |

signed right shift | >>> | a>>> |

###
**Other operators:**

- a dot (.) operator is used to access member elements of an object.like student.getName().It is also used to access the classes and sub package from a package
- a parenthesis () operator determines the precedence of operator inside them
- a square [] operator is used for array indexing.
- a comma operator is used as a separator in function argument lists,it is also used in for loop for sequential evaluation.

If we try to use arithmetic operators on boolean data type,compiler will throw a compilation error.The operator-operator name is undefined for the argument type boolean.

```
boolean a=true;
boolean b=false
a=a+b;// compile time error
```

All About Operators in Java
Reviewed by Animesh Chatterjee
on
October 24, 2018
Rating:

## No comments: