Operators


Operators

Java has a rich set of operators to change variable values. Operators can be classified into the following groups
Arithmetic Operators: Used for performing mathematical operations.

Operator
Explanation

+

adds two operands

-

subtracts second operand from first

*

multiplies two operands

/

divides numerator by denominator

%

gives the remainder

++

increment operator increases integer value by one

--

decrement operator increases integer value by one


Example No.1:

Com.knowledge2life public class Main { public static void main(String[] args) { int a = 13, b = 6; // addition operator System.out.println("Knowledge2life " + (a + b)); // subtraction operator System.out.println("Knowledge2life " + (a - b)); // multiplication operator System.out.println("Knowledge2life " + (a * b)); // division operator System.out.println("Knowledge2life " + (a / b)); } }

OUTPUT:

Knowledge2life 19
Knowledge2life 7
Knowledge2life 78
Knowledge2life 2

Relational Operators: Used to compare two variables or values

Operator
Explanation

==

Check if two operands are equal

!=

Check if two operands are not equal

>

Checks whether the left value is greater than right value

<

Checks whether the left value is smaller than right value

>=

Checks whether the left value is greater than or equal to right value

<=

Checks whether the left is smaller then or equal to right value.


Bitwise Operators: Used to perform operations bit by bit

Operator
Explanation

&

Bitwise AND

|

Bitwise OR

^

Bitwise EXCLUSIVE OR

<<

Left shift

>>

Right shift

Logical Operators: Used to check conditional expressions

Operator
Explanation

&&

Logical AND

||

Logical OR

!

Logical NOT

Assignment Operators: Used to assign a value to a variable

Operator
Explanation

=

Used to assign values from right side operands to left side operand

+=

Used to add right value to the left value and assign the result to left

-=

Used to subtract right value from the left value and assign the result to left

*=

Used to multiply right value to the left value and assign the result to left

/=

Used to divide right value to the left value and assign the result to left

%=

Calculates modulus using the operands and assign the result to left

Example:

Com.knowledge2life public class Main { public static void main(String[] args) { int a = 10; int var; var = a; System.out.println("Knowledge2life " + var); // assign value using =+ var += a; System.out.println("Knowledge2life " + var); // assign value using =* var *= a; System.out.println("Knowledge2life " + var); } }

OUTPUT:

Knowledge2life 10
Knowledge2life 20
Knowledge2life 200

Misc Operators

Operator
Explanation

?:

Returns true or false value

instanceof

Returns true or false value