# Operators in Java

Java provides a rich set of built-in operators which can be categorized as follows.

• Arithmetic Operators
• Relational Operators
• Increment and Decrement Operators
• Logical Operators
• Assignment Operators

## Arithmetic Operations

Arithmetic Operators are the operators which perform arithmetic calculations on operands same as these are used in algebra.

In the following table, the value of 'a' is 8 whereas that of 'b' is 4.

Operator Description Example
- Subtracts second operand from the first a-b=4
* Multiplies both operands a*b=32
/ Divides numerator by denominator. a/b=2
% Modulus Operator returns the remainder of after an integer division. a%b=0
```class O1{
public static void main(String[] args){
int a=10, b=2;
System.out.println("a+b = " + (a+b));
System.out.println("a-b = " + (a-b));
System.out.println("a*b = " + (a*b));
System.out.println("a/b = " + (a/b));
}
}
```
a+b = 12
a-b = 8
a*b = 20
a/b = 5

int a=10, b=12; - As discussed earlier, int a=10; will first allocate space for 'a' in memory and then give it a value 10. Same will be done for b and will be given a value 2.

Here, "a+b = " is written inside (" "). Whatever is written inside " " is not evaluated and will be printed as it is. So, a+b = will not be evaluated and get printed as it is. Then (a+b) after + will be evaluated (i.e. 12) and printed.

So, "a+b = " will combine with the calculated value of a+b i.e. ( 10+2 i.e. 12 ) and printed as a+b = 12

We can also do:

```class O2{
public static void main(String[] args){
int a=10, b=2, z;
z = a+b;
System.out.println("a+b = "+z);
}
}
```
a+b = 12

Here, z will become a+b i.e. 12. And in 'println', 'a+b = ' is inside " ", so it will be printed as it is ( without evaluation ) and then the value of z i.e. 12 will be printed. So, a+b = 12 will get printed.

When an integer is divided by another integer, the answer is rounded off to the nearest integer.

For example, 3/2 returns 1 whereas 2/3 returns 0.

If at least one of numerator or denominator has a decimal, then we will get the exact decimal value of the answer.

All 3/2.0, 3.0/2 and 3.0/2.0 return 1.5.

```class O3{
public static void main(String[] args){
System.out.println("3 / 2     = " + (3 / 2));
System.out.println("3 / 2.0   = " + (3 / 2.0));
System.out.println("3.0 / 2   = " + (3.0 / 2));
System.out.println("3.0 / 2.0 = " + (3.0 / 2.0));
}
}
```
3 / 2 = 1
3 / 2.0 = 1.5
3.0 / 2 = 1.5
3.0 / 2.0 = 1.5

As we have seen now that 3/2 ( both int ) is giving 1 whereas 3.0/2 or 3/2.0 or 3.0/2.0 ( at least one is double ) is giving us 1.5.

So now think, if we are using int for some variable and at some point of our code we need double, then we can easily achieve it with type-casting as discussed in the previous chapter. An example on this is:

```class O4{
public static void main(String[] args){
int x = 10, y = 3;
double z = 4.5;
System.out.println(x/y);
System.out.println((int)z);
System.out.println((double)x/y);
}
}
```
3
4
3.3333333333333335

As discussed earlier, we have type casted z to int ( (int)z ). And x to double ( (double)x ) to give a double value after the division.

## Relational Operators

Following are the relationship operators in Java which return true if the relationship is true and false if the relationship is false.

In the following table, assume the value of 'a' to be 8 and that of 'b' to be 4.

Operator Description Example
== Equal to (a == b) is false
!= Not equal to (a != b) is true
> Greater than (a > b) is true
< Less than (a < b) is false
>= Greater than or equal to (a >= b) is true
<= Less than or equal to (a <= b) is false

Let's look at an example to see the use of these.

```class O5{
public static void main(String[] args){
int a=10, b=25;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
```
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

This example is on the above table.
Since
a is not equal to b, so a == b gave us false and a != b ( a not equal to b ) gave us true
Similarly, since a is smaller than b,
so a > b gave us false and a < b gave us true.
Same with >= ( greater than equal to ) and <= ( less than equal to ).

## Difference between = and ==

= and == perform different operations. = is the assignment operator while == is the equality operator.

= assigns values from its right side operands to its left side operands whereas == compares values.

By writing x = 5, we assign a value of 5 to x, whereas by writing x == 5, we check if the value of x is 5 or not.

So, == gives us true if both operands are same and false, if both are not. In Java programming, if we are writing A and B, then the expression is true if both A and B are true. Whereas, if we are writing A or B, then the expression is true if either A or B or both are true.

A and B - Both A and B.

A or B - Either A or B or both.

Symbol for AND is && while that of OR is ||.

Let the value of 'a' be 4 and that of 'b' be 0.

Operator Description Example
&& Logical AND. If both the operands are 1, then the condition becomes true (3>2)&&(4>8) is false
|| Logical OR. If any one or both the operands are 1, then the condition becomes true (3>2)||(4>8) is true
! Logical NOT. It is used to reverse the condition. So, if a condition is true, ! makes it false. !(3>2) is true

In Logical AND (&&) operator, if any one of the expressions is false, the condition becomes false. Therefore, for the condition to become true, both the expressions must be true.

For example, (3>2)&&(5>4) returns true because both the expressions are true. Conditions (3>2)&&(5<4), (3<2)&&(5>4) and (3<2)&&(5<4) are false because one of the expressions is false in each case.

For Logical OR (||) operator, the condition is false only when both the expressions are false. If any one expression is true, the condition returns true. Therefore (3<2)||(5<4) returns false whereas (3>2)||(5<4), (3<2)||(5>4) and (3>2)||(5>4) returns true.

Logical Not (!) operator converts true to false and vice versa. For example, !(4<7) is true because the expression (4<7) is false and the operator ! makes it true.

```class O6{
public static void main(String[] args){
int a=10, b=0;
System.out.println("!(a>b) = " + !(a>b) );
System.out.println("(a>b) && (b==0) = " + ((a>b) && (b==0)) );
System.out.println("(a>b) && !(a == 10) = " + ((a>b) && !(a==10)) );
}
}
```
!(a>b) = false
(a>b) && (b==0) = true
(a>b) && !(a == 10) = false

In the above example, since the value of 'a>b' is true. So, !(a>b) makes it false.

(a>b) && (b==0) - b==0 is true and a > b is also true (since a is greater than b). Thus, (a>b) && (b==0) is true && true i.e. true as both the operands are true.

## Assignment Operators

Java provides the following assignment operators which assign values from its right side operands to its left side operands.

For example, a = 5; assigns a value of '5' to the variable 'a'.

= operator makes the left operand equal to the right one. This means that x=y will make x equal to y and not y equal to x.

Before going further, try this example:

```class O7{
public static void main(String[] args){
int a=10;
System.out.println(a);

a = a+2;
System.out.println(a);

a = a*2;
System.out.println(a);

a = a-2;
System.out.println(a);

}
}
```
10
12
24
22

a = 10; - In this line, a is 10. So, 10 is printed from the first 'println'.
a = a+2 - Remember, we discussed that = makes the left operand equal to the right. In the right side, we have a+2. So, a+2 will be calculated i.e. 12 thus making the expression equivalent to a = 12;. So, now a is 12. Therefore, 12 is printed from the second 'println'. And now a is 12.
After that a = a*2; - In the right side, we have a*2. So, it will be evaluated as 12*2 i.e. 24 thus making the expression a = 24;. So, a is 24 now and 24 will be printed from the third 'println'.

Operator Description Example
= Assigns value of right operand to the left operand C = A+B is same as C = A + B
+= Adds the value of right operand to the left operand and assigns the final value to the left operand C += A is same as C = C + A
-= Subtracts the value of right operand to the left operand and assigns the final value to the left operand C -= A is same as C = C - A
*= Multiplies the value of right operand to the left operand and assigns the final value to the left operand C *= A is same as C = C * A
/= Divides the value of left operand from the right operand and assigns the final value to the left operand C /= A is same as C = C / A
%= takes modulus using two operands and assigns the result to the left operand C %= A is same as C = C % A
We cannot assign any value to a constant. For example, 4 = c will give an error.

4 = c will try to make 4 as c, but it is not possible.

Suppose the value of an integer variable 'a' is 8. When we write a += 2, this is equivalent to a = a + 2, thus adding 2 to the value of 'a' and making the value of 'a' equal to 10.

Similarly, a -= 2 equals the expression a = a - 2, thus subtracting 2 from the value of 'a' and then assigning that value to 'a'

Similarly, we can perform other operations of multiplication and division.

```class O8{
public static void main(String[] args){
int a=10;
System.out.println("a = 5 " + "Value of a = " + a);
System.out.println("a += 5 " + "Value of a = " + (a+=5) );
System.out.println("a -= 5 " + "Value of a = " + (a-=5) );
System.out.println("a *= 5 " + "Value of a = " + (a*=5) );
System.out.println("a /= 5 " + "Value of a = " + (a/=5) );
System.out.println("a %= 5 " + "Value of a = " + (a%=5) );
}
}
```
a = 5 Value of a = 10
a += 5 Value of a = 15
a -= 5 Value of a = 10
a *= 5 Value of a = 50
a /= 5 Value of a = 10
a %= 5 Value of a = 0

## Increment and Decrement Operators

++ and -- are called increment and decrement operators respectively.

++ adds 1 to the operand whereas -- subtracts 1 from the operand.

a++ increases the value of a variable 'a' by 1 and a-- decreases the value of a by 1.

Similarly, ++a increases the value of 'a' by 1 and --a decreases the value of a by 1.

In a++ and a--, ++ and -- are used as postfix whereas in ++a and --a, ++ and -- are used as prefix.

For example, suppose the value of a is 5, then a++ and ++a changes the value of 'a' to 6. Similarly a-- and --a changes the value of 'a' to 4.

## Difference between Prefix and Postfix

While both a++ and ++a increases the value of 'a', the only difference between these is that a++ returns the value of 'a' before the value of 'a' is incremented and ++a first increases the value of 'a' by 1 and then returns the incremented value of 'a'.

Similarly, a-- first returns the value of 'a' and then decreases its value by 1 and --a first decreases the value of 'a' by 1 and then returns the decreased value.

An example will make the difference clear.

```class O9{
public static void main(String[] args){
int a=10,b=10,c=10,d=10;
System.out.println("value of a++ = " +(a++));
System.out.println("a = "+a);
System.out.println("value of ++b = " +(++b));
System.out.println("value of c-- = " +(c--));
System.out.println("value of --d = " +(--d));
}
}
```
value of a++ = 10
a = 11
value of ++b = 11
value of c-- = 10
value of --d = 9

As just saw that in the first 'println', 10 is printed and then its value increased to 11. In the second 'println', 11 got printed. But with ++b, b first got increased to 11 and then printed on screen.

## Precedence of Operators

In Maths, you might have learned about BODMAS rule, but that rule is not applied here. If we have written more than one operation in one line, then which operation should be done first is governed by the following rules :- Expression inside brackets '()' are evaluated first. After that, this table is followed ( The operator at the top has higher precedence and that at the bottom has the least precedence ):

Operator Associativity
++ -- ! Right to left
* / % Left to right
+ - Left to right
> >= < <= Left to right
== != Left to right
&& Left to right
|| Left to right
= += -= *= /= %= Right to left

Consider an example.

n = 3 * 4 + 5

The priority order of the multiplication operator ( * ) is greater than that of the addition operator ( + ). So, first 3 and 4 will be multiplied and then 5 will be added to their product. Thus the value of n will be 17.

If two operators are of same priority, then evaluation starts from left or right as stated in the table.
e.g.-
k = 8/4+3-5*6+8
Solving, '*' and '/' first from left to right.
k = 2+3-30+8
Now solving, '+' and '-' from left to right
k = -17
Now solving '=' from right to left

If you don't want to remember these rules, then just put the expression you want to execute first in brackets. Eg- If you want to divide the product of (2+2) and 444 by the quotient (999/5), then write the expression as - ((2+2)*444)/(999/5). This will get evaluated as (4*444)/(999/5) and finally get simplified to 1776/199 (since 999/5 is 199 and not 199.8).

### Let's import maths

What if you want to take out the sine, cos or log of a number ?

Java allows us to perform such mathematical operations.

If you are not aware of these mathematical functions, then don't go into these and continue your coding.

In Java, we can perform such mathematical operations with the help of Math class. Java has a number of predefined classes which we can use about which we will learn later.

Predefined classes are organized in the form of packages. This Math class comes under java.lang package. So we first need to import java.lang package in our program.

We use import keyword to import any package in our program. We can either import the java.lang.Math class or the entire java.lang package.

So we have to add one of the following code in the beginning of our program before the main class.

import java.lang.*;

Here '.*' imports all the classes of java.lang package.

import java.lang.Math;

java.lang.Math will only import Math from lang package.

After importing the Math class, we can now enjoy the different mathematical functions in Java. These functions are called methods of Math class.

Some of those functions are listed below.

Math functions Description
Math.sin() Calculates the sine value of some angle in radians
Math.cos() Calculates the sine value of some angle in radians
Math.abs() Calculates the absolute value of a number
Math.ceil() Calculates the floating value of a number which is equal to the integer just greater than it
Math.floor() Calculates the floating value of a number which is equal to the integer just smaller than it
Math.min() Returns the smaller number among the two numbers passed to it
Math.max() Returns the larger number among the two numbers passed to it
Math.round() Rounds a float or a double to the nearest integer
Math.sqrt() Calculates the square root of a number
Math.pow() It takes two numbers and returns the value of the first number raised to the power equal to the second parameter
Math.log() Returns the logarithm of a number.

Now let's have a look at some of these functions with their examples.

#### Math.abs()

It returns the absolute value of the number passed to it. Absolute value of a number is the magnitude of the number with a positive sign. For example, the absolute value of 2 is 2 whereas the absolute value of -2 is also 2.

To take out the absolute value of -2.3, we have to write the following code.

```import java.lang.Math;
class Test
{
public static void main(String[] args)
{
System.out.println(Math.abs(-2.3));
}
}
```
2.3

#### Math.ceil()

It calculates the floating value of a number which is equal to the integer just greater than it. For example, if the number 3.45 is passed to the function, it will return 4.0.

```import java.lang.Math;
class Test
{
public static void main(String[] args)
{
System.out.println(Math.ceil(3.4));
}
}
```
4.0

#### Math.pow()

It takes two numbers and returns the value of the first number raised to the power equal to the second parameter.

For example, the value of the number 3 raised to the power 2 is equal to multiplying three two times which is equal to 9 (= 3*3).

```import java.lang.Math;
class Test
{
public static void main(String[] args)
{
System.out.println(Math.pow(5,3));
}
}
```
125.0

Java will be much more fun when you will learn more. Making of android apps is one of the most interesting applications of Java.

A lot of things are discussed here. So, solve questions from the practice section to have a good command over them.

Talent is good, Practice is better, and Passion is Best
-Frank Lloyd Wright  