## 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 result in the same. All operators produce 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 effects.

In general, operations mainly classified into two categories:

**Transitive****Non-Transitive**

When x(operator)y(operator)z=z(operator)y(operator)x then the operation is transitive operation. Otherwise, it is a non-transitive operation.

```
//for x=2,y=4,z=8 and operator=+ then
x+y+z=2+4+8=14
//is equal to
x+y+x=8+4+2=14
//hence it is a transitive operation.
//in case operator1 =+ and operator2=-
x+y-z=2+4-8=-2
//is not equal to
z+y-x=8+2-2=8
//hence it is non transitive operation.
```

### 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**

when one of the operands is real and others in other types, the expression is called a mixed-mode arithmetic expression. The compiler will check for a higher type of the operands and converts the lower type to a higher type and carry out the operation.

```
=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 an addition |

Subtraction | – | a-b | Subtracts right from left |

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

Division | / | a/b | |

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

**Concatenation operator:**

only operator that supports operator overloading in java. In normal context ‘+’ works as an addition but in String context, it works as a concatenate. If an expression begins with a String, then all operands that follow must be String.

```
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);
}
}
```

The output of the code:

$javac MyStringTest.java

$java -Xmx128M -Xms16M MyStringTest

i j k 123

6 i j k

As the expression begins with the 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 the concatenation |

**Assignment operator**

They are mainly classified as:

- 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 |

No space between op and =will be allowed and generic syntax is identifier op=expression. It is also called shorthand operator, as it follows shorthand notations.

**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 in a more efficient code.

**Unary operator**

The unary plus and minus operators are the same as binary plus and minus. The unary minus produces the negative of the value. Unary plus provides symmetry with unary plus

```
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 |

++ and — is also called Autoincrement and Auto decrement operators. They have two flavors of it.

- 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**

The relational operator generates a boolean result. They evaluate the relationship between the values of the operands. A relational expression produces true if the relationship is true and false otherwise. Equivalence and non-equivalence work well with all build-in data types but other comparisons won’t work with type boolean.

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

not | ! | !a | logical complement operator inverts the value of 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 |

These operators can be applied to any type of data and only returns true or false. when arithmetic expressions are used on either side of a rational operator, the arithmetic expression will be evaluated first then the result is compared. Thus Arithmetic operators will have higher priority over rational operators.

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

Relational operators are used in decision statements such as if, while etc to decide the next course of action.

### Compound Operator:

++ and — are called the compound operators and can not have space in between.

**Conditional operator or Logical Operator:**

They are also called logical operators. It produces a boolean result as true or false based on the logical relationship of its arguments. They can be used in the boolean context, not for other data types. They are used when we want to form compound conditions by combining two or more relations.

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 generates a false output, the whole expression becomes false, irrespective of the yield of the other functions.Java will not execute 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

it is known as arithmetic if the operator having a symbol **?:**.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 easy 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**

instanceOf compares an object to a specified type. It returns a boolean value. The instanceOf is an object reference operator and returns true if the object on the left-hand side is an instance of the class given on the right-hand side.

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

They return true if the student is an instance of Student or Triangle is an instance of Shape.

**Bitwise operator**

Bitwise operator allows us to manipulate bits in an integral primitive data type. Bitwise operators perform Boolean algebra on the corresponding bits in the two arguments to produce a result. The Bitwise operators are often manipulating hardware directly and have to set the bits in hardware registers.Java was originally designed to be embedded in TV set-top boxes and so this low-level orientation still makes sense!!.

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 a unary operator.

It only takes one argument(all other bitwise operators are binary operators). 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 use the same character as bits are small. There is only one character in the bitwise operator.

Bitwise operators can be combined with =,&=,|=,^=. ~ is a unary operator and can not be combined with = sign. The boolean type is treated as a one-bit value so it is somewhat different. We can perform a bitwise AND, OR, XOR but can perform NOT.

**Shift operator**

The shift operators also manipulate bits. They can only be used on primitive integral types. The left shift operator(<<) produces the operand to the left of the operator shifted to the left by the number of bits specified after the operator. (By inserting zeros at the lower order bits).

The signed right shift operator(>>) produces the operand to the left of the operator shifted to the 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, the 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 subpackage 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, the 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
```

learn more about operator precedence here.

### Golden Rules for Type Casting While Working With Arithmetic Operator

Arithmetic Operators: |

In java +,-,*,/,% are called arithmetic operators. The arithmetic operator is used on two operands of the same type or different types(applicable)

Like-

int a=10; int b=10; int c=a+b; System.out.print(c);

output-20

But if we take some different example like–

int a=10; double b=10.00; int c=a+b; System.out.print(c);

output:

possible loss of precision

found: double

required: int

int c=a+b;

^

Now, this looks very confusing. Is n’t? in variable b we are only assigning value 10, which can be considered as valid int. still compiler is not approving the arithmetic operations.

if you are thinking that the second case failed as the operand types are different and the first case passed as two operands were of the same type, please check out the below code

byte a=10; byte b=20; byte c=a+b; System.out.print(c);

output:

possible loss of precision

**found: int**

required: byte

byte c=a+b;

^

The most confusing part is the two operands are of type(byte) but still, compiler found ** int type**.

Java compiler is too complicated???

Arithmetic Operators Rule: |

Let us see the data types (primitive ) in java.

datatypes as per capacity byte being smallest and double being the highest |

If we apply any arithmetic operator between two operands say x,y then the result type should follow the below-written rule

**MAX(int, the datatype of the first operand, the datatype of the second operand)**

so for all arithmetic operation, the above rule will be applicable.

let’s take the third example…

byte a=10; byte b=20; byte c=a+b; System.out.print(c);

so for this case–the right side datatype evaluation will be…

as per rule-

Max(int,byte,byte)

Now as per the diagram among int, byte, and byte the max is int, hence the right-hand side datatype evaluation will be int.

please check the compiler error message–found int.

the second point is here the int is being assigned to byte whose capacity is lower than int. So the compiler is rightly pointing out–“possible loss of precision”

For a quick reference let us see the output datatype for a few mixed case…

Datatypes of the first operand and the second operand | output datatype |

byte+byte | int |

byte+short | int |

char+char | int |

long+int | long |

float+long | float |

double+int | double |

double+any | double |

The only thing if one of the data types is a string then these rules will not be applicable.

### 4 Rules to Remember While Working With Incremental And Decremented Operator in Java

In java the ‘++’ operator is called incremental and ‘–‘ operator is called the decremental operator. Again Incremental can be divided

- pre-increment (y=++x)
- Post increment (y=x++)

in pre-increment, the value of the variable is incremented first and then assign to y.

in post-increment, the value is assigned first then its value is incremented.

Similarly, for decrement, we have

- pre decrement (y=–x)
- post decrement (y=x–)

Now, most importantly the rules are…

Increment and decrement operator can only be applied to the variable but not for any constant values… |

int x=10; int y=++x; System.out.println(y)

This code works fine but…

int x=10; int y=++10; System.out.println(y)

this code will throw a compile-time error.

Error: Unexpected type

found: value

required: variable

Nesting of increment and decrement operator is not allowed in java |

Let me give some piece of code…

int x=10; int y=++(++x); System.out.println(y);

This is also not accepted why?

well (++x)will execute perfectly and after that the equation becomes…

y=++11

violating the first rule…hence it will throw the same error.

Increment and decrement operator is not allowed for the final variable in java |

Check out here for the importance of a final variable.

for normal variable- this is valid

int x=6; x++; ++x;

but if that is the final variable…these expressions are invalid.

final int x=6; x++; ++x;

It will throw a compile-time error…

Increment and decrement operator can be applied to all primitive data types except Boolean in java |

*for int::*

int x=6; ++x; System.out.println(x);

output is 7

*for char::*

char ch ='c'; ch++; System.out.println(ch);

the output is’

*for double::*

double d=12.5; d++; System.out.println(d);

output is 13.5

*for Boolean::*

Boolean b=true; b++; System.out.println(b);

output:

Compile-time error

byteTest.java:6: incompatible types

found: boolean

required: java.lang.Boolean

operator ++ cannot be applied to java.lang.Boolean

### Operator Precedence in Java

I have talked about Operators in java. In this post, we will look into the operator precedence. Operator precedence defines how an expression evaluates when several operators are present in a statement. Java has specific rules that determine the order of evaluation. It is very tough to remember the rules and priorities of the operators. In general, we use parenthesis “()” to make the order of evaluation explicitly.

**Evaluation of expression:**

Expressions are evaluated and stored in a variable.The general form is variableName=expression.

Expressions are evaluated first and stored to the left-hand-side variable. like:

```
x=m*n+d*c;
```

There could be a chance to have extra blank space around the operators. They are just to improve readability(expect shorthand operators). we use these statements, the variables m,n,d,c must be declared beforehand.

**The rules:**

- An arithmetic expression without any parenthesis will be evaluated first from left to right using the rule of precedence. High priority is given for * and/and low priority is given for + and -.
- The arithmetic expression operates on two passes. In the first pass, all the high priority operators (if any) are applied and calculated. During the second pass, the low priority operators (if any) are applied and evaluated.

```
//if an expression is given
x=a-b/3+c*2-1;
//and values of a=9,b=12,c=3
x=9-12/3+3*2-1;
```

the first pass will transform the expression as :

```
//step-1
x=9-4+3*2-1;
//step-2
x=9-4+6-1;
```

The second pass will transform it as :

```
//step-3
x=5+6-1;
//step-4
x=11-1;
//step-5
x=10;
```

- In case there exist a parenthesis, the evaluation changes as it gets higher priority. They will be evaluated from most left to right.if the expression is given as:

```
x=a-b/(c+c)*(2-1)
```

then the first pass will yield

```
//step-1
x=9-12/6*(2-1)
//step-2
x=9-12/6*1
```

the second pass will be calculated as :

```
//step-3
x=9-2*1
//step-4
x=9-2
//step-5
x=7
```

- There could be a chance of nested parenthesis. In that case, the innermost parenthesis will be calculated first then it will go words outer most parenthesis. Inside the parenthesis, the generic rule will be applied.

```
x=a-(b/(c+c)*2)-1
```

Here is the rule for operator precedence in java:

Operator | category | Description | Association | Rank |
---|---|---|---|---|

. | Special | member selection | left to right | 1 |

() | Special | function call | left to right | 1 |

() | Special | parenthesis | left to right | 1 |

[] | Special | array element reference | left to right | 1 |

~ | One’s compliment | one’s compliment | right to left | 2 |

(type) | Typecasting | type casting | right to left | 2 |

++ | Increment | Increment | right to left | 2 |

— | Decrement | decrement | right to left | 2 |

! | Logical not | logical not | right to left | 2 |

– | Urinary minus | Urinary minus | right to left | 2 |

* | Arithmetic operator | Multiplication | left to right | 3 |

/ | Arithmetic operator | Division | left to right | 3 |

% | Arithmetic operator | modulus | left to right | 3 |

+ | Arithmetic operator | addition for integral and concatenation for String | left to right | 4 |

– | Arithmetic operator | subtraction for integral | left to right | 4 |

<< | Bitwise operator | the left shift for integral | left to right | 5 |

>> | Bitwise operator | the right shift for integral | left to right | 5 |

>>> | Bitwise operator | right shift with zero fill for integral | left to right | 5 |

< | Relational operator | less than | left to right | 6 |

<= | Relational operator | less than equal to | left to right | 6 |

> | Relational operator | greater than | left to right | 6 |

>= | Relational operator | greater than equal to | left to right | 6 |

instanceOf | Type comparison | Type comparison for object and type | left to right | 6 |

== | Equality | Equality for object and primitive | left to right | 7 |

!= | Inequality | Inequality for object and primitive | left to right | 7 |

& | Bitwise operator | Bitwise AND for integral and boolean | left to right | 8 |

^ | Bitwise operator | Bitwise XOR for integral and boolean | left to right | 9 |

| | Bitwise operator | Bitwise OR for integral and boolean | left to right | 10 |

&& | Logical operator | logical AND | left to right | 11 |

|| | Logical operator | logical OR | left to right | 12 |

?: | Ternary operator | Ternary operator-boolean, any any | right to left | 13 |

= | Assignment operator | Assignment operator | right to left | 14 |

op= | Shorthand operator | Shorthand operator *=,/=,%=,+=,-=,<<=,>>=,>>>=,&=,^=,|= | right to left | 15 |

Thinking in java came up with a unique way to remember the operator precedence: Credit to the author Bruce Eckel:

Mnemonics | Operator type | Operator |
---|---|---|

Ulcer | Unary | +,-,++ etc |

Addicts | Arithmetic and shift | *,/,+,-,<<,>> |

Really | Relational | >,<.>=,<=,==,!= |

Like | Logical and bitwise | $$,||,&,|,^ |

C | Conditional | A>B? x:y |

A lot | Assignment | =,*= |

### Important points to remember

- Java does not support the comma operator(,) for combining two expressions into one. (Exception -for loop)
- Java does not support pointer directly hence there is no operator like*,->,& or size of
- Java does not consider [] array access and . (dot) for field access to be operators.
- Because all integral types in java are signed values. The java >> operator is defined to do a right shift with sign extension.
- The >>> operator treats the value to be shifted as an unsigned number and shifts the bits right with zero extension.
- When & and | are applied to integral types in java, they perform the expected bitwise AND and bitwise OR operation.
- Java makes a strong distinction between integral types and boolean types. If these operators are applied to boolean types, they perform logical AND and logical OR operations. These logical AND and logical OR operators always evaluate both their operands, even when the result of the operation is determined after evaluating only the left operand. They are useful when we want the side effect to happen. However, if we do not want the right operand evaluated if it is not necessary, we can use && or || operators as they operate on short-circuited logic.
- The &= and |= operators perform a bitwise or logical operation depending on the type of the operands.

#### The operator Precedence controls

Operator precedence controls the order in which operations are performed.

```
a=b+c*d
```

Here * is having higher precedence than + operator so c*d is evaluated first and = (assignment operator) is having lower precedence than + hence it will be evaluated or performed last.

Operators with the same precedence as addition and subtraction or multiplication or division are performed to their associations.

(Left to right.)

Operator precedence can be overridden with explicit use of the parentheses.

```
a=(b+c)*d
```

in this case (b+c) is evaluated first followed by multiplication and assignment.

Two cases to remember- Unary operators and ternary conditions i.e ?: operators have right to left association.

```
x=~-~y=>x~(~y)
p=a?b:c?d:e:f:g=>a?b:(c:d:(e?f:g))
```

### The instanceOf operator

The instanceOf operator returns true if the object on the lefthand side is an instance of the class or implements the interface of the right-hand side. Otherwise, it returns false. If the left-hand side is null, it also returns false.

The instance of the operator is used to verify the class of an object.

`Syntax-if (Object instanceOf type)`

Object – Object is an instance of a class.

Type-Type is a class type.

If the condition satisfies, the operator returns true, otherwise returns false.

### What Is The Difference Between ++x And x=x+1 or –x And x=x-1?

This is the most interesting question is What Is the difference between ++x and x=x+1 while working with java.

both the statement does the same thing–increment the value of x by 1.

Then the doubts come

- If both they do the same thing why we will have two statements?
- If they are different then how?
- Which one is more efficient?

Let us discuss the concept with some example…

public class operatortest { public static void main(String[] Args) { int x=4; ++x; System.out.println(x); } }

output->5

now if we change the statement like–

public class operatortest { public static void main(String[] Args) { int x=4; x=x=1; System.out.println(x); } }

output->5 only

Till now no problem if the datatypes are int/long/double

but say the datatype changes now…

instead of int if we use char/byte/short??

let us see…

public class operatortest { public static void main(String[] Args) { byte x=4; x=x=1; System.out.println(x); } }

very quickly we will get a compile-time error…

if you are running through DOS prompt.

you can see compile error-possible loss of precision

public class operatortest { public static void main(String[] Args) { byte x=4; ++x; System.out.println(x); } }

output–5

So no problem with ++ operator.

So the answer of questions are even though we have x++ and x=x+1 statement, they have the same purpose. But in case of ++ or — operator internal type casting is performed by the compiler, but in case of the normal operators, the developer needs to do typecasting explicitly. hence ++,– operators are most efficient. |

It’s a pity you don’t have a donate button! I’d definitely donate to this brilliant blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will talk about this website with my Facebook group. Chat soon!

I am curious to find out what blog system you happen to be using?

I’m experiencing some minor security issues with my latest

site and I’d like to find something more safe.

Do you have any suggestions?