2.java Mathematics - Operators
2.java Mathematics - Operators
Operators in Java
Java provides many types of operators which can be used according to the need.
They are classified based on the functionality they provide. Some of the types are-
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
10. Precedence and Associativity
Arithmetic Operators: They are used to perform simple arithmetic operations on primitive
data types.
*: Multiplication
/: Division
%: Modulo
+: Addition
–: Subtraction
Unary Operators: Unary operators need only one operand. They are used to increment,
decrement or negate a value.
–: Unary minus, used for negating the values.
+: Unary plus, indicates positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is byte, char, or short. This is called unary numeric promotion.
++: Increment operator, used for incrementing the value by 1. There are two
varieties of increment operator.
Post-Increment: Value is first used for computing the result and
then incremented.
Pre-Increment: Value is incremented first and then result is
computed.
—: Decrement operator, used for decrementing the value by 1. There are two
varieties of decrement operator.
Post-decrement: Value is first used for computing the result and
then decremented.
Pre-Decrement: Value is decremented first and then result is
computed.
!: Logical not operator, used for inverting a Boolean value.
Assignment Operator: ‘=’ Assignment operator is used to assign a value to any variable.
It has a right to left associativity, i.e value given on right hand side of operator is
assigned to the variable on the left and therefore right hand side value must be declared
before using it or should be a constant.
General format of assignment operator is,
variable = value;
In many cases assignment operator can be combined with other operators to build a
shorter version of statement called Compound Statement. For example, instead of
a = a+5, we can write a += 5.
+=, for adding left operand with right operand and then assigning it to
variable on the left.
-=, for subtracting left operand with right operand and then assigning it to
variable on the left.
*=, for multiplying left operand with right operand and then assigning it to
variable on the left.
/=, for dividing left operand with right operand and then assigning it to
variable on the left.
%=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.
Relational Operators: These operators are used to check for relations like equality,
greater than, less than. They return Boolean result after the comparison and are
extensively used in looping statements as well as conditional if else statements. General
format is,
// ternary operator.
public class operators {
// numbers
? (a > c)
?a
:c
: (b > c)
?b
: c);
+ result);
}}
Output:
Max of three numbers = 30
Bitwise Operators: These operators are used to perform manipulation of
individual bits of a number. They can be used with any of the integer types. They
are used when performing update and query operations of Binary indexed tree.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit by bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e. with all
bits inversed.
Shift Operators: These operators are used to shift the bits of a number left or right
thereby multiplying or dividing the number by two respectively. They can be
used when we have to multiply or divide a number by two. General format-
number shift_op number_of_places_to_shift;
<<, Left shift operator: shifts the bits of the number to the left and fills
0 on voids left as a result. Similar effect as of multiplying the number
with some power of two.
>>, Signed Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit depends on
the sign of initial number. Similar effect as of dividing the number with
some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.
instance of operator : Instance of operator is used for type checking. It can
be used to test if an object is an instance of a class, a subclass or an
interface. General format-
// instance of operator
class operators {
}}
class Person {
interface MyInterface {
Output:
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true
Precedence and Associativity of Operators
Precedence and associative rules are used when dealing with hybrid equations involving
more than one type of operator. In such cases, these rules determine which part of the
equation to consider first as there can be many different valuations for the same equation.
The below table depicts the precedence of operators in decreasing order as magnitude with
the top representing the highest precedence and bottom shows the lowest precedence.
// (* = / = %) > (+ = -)
// prints a+(b/d)
System.out.println("a+b*d-e/f = "
+ (a + b * d - e / f));
}}
Output:
a+b/d = 20
a+b*d-e/f = 219
Using + over (): When using + operator inside system.out.println() make sure to do addition using parenthesis. If
we write something before doing addition, then string addition takes place, that is associativity of addition is left to
right and hence integers are added to a string first producing a string, and string objects concatenate when using +,
therefore it can create unwanted results.
int x = 5, y = 8;
// concatenates x and y as
+ x + y);
// addition of x and y
+ (x + y));
}}
Output:
Concatenation (x+y)= 58
Addition (x+y) = 13
Arithmetic Operators
These operators involve the mathematical operators that can be used to perform various
simple or advance arithmetic operations on the primitive data types referred to as the
operands. These operators consist of various unary and binary operators that can be applied
on a single or two operands respectively. Let’s look at the various operators that Java has to
provide under the arithmetic operators.
import java.io.*;
class Addition {
// initializing variables
}}
Output:
num1 = 10
num2 = 20
The sum = 30
2. Subtraction(-): This operator is a binary operator and is used to subtract two
operands.
Syntax:
num1 - num2
Example:
num1 = 20, num2 = 10
sub = num1 - num2 = 10
// Java code to illustrate Subtraction operator
import java.io.*;
class Subtraction {
// initializing variables
}}
Output:
num1 = 20
num2 = 10
Subtraction = 10
3. Multiplication(*): This operator is a binary operator and is used to multiply two
operands.
Syntax:
4. num1 * num2
Example:
class Multiplication {
// initializing variables
}}
Output:
num1 = 20
num2 = 10
Multiplication = 200
5. Division(/): This is a binary operator that is used to divide the first
operand(dividend) by the second operand(divisor) and give the quotient as
result.
Syntax:
num1 / num2
Example:
class Division {
// initializing variables
}}
Output:
num1 = 20
num2 = 10
Division = 2
6. Modulus(%): This is a binary operator that is used to return the remainder
when the first operand(dividend) is divided by the second operand(divisor).
Syntax:
num1 % num2
Example:
num1 = 5, num2 = 2
class Modulus {
// initializing variables
Output:
num1 = 5
num2 = 2
Remainder = 1
7. Increment (++): This is a unary operator that acts on one operand, unlike the
previous operations. It is used to increment the value of an integer. It can be
used in two ways:
1. Post-increment operator: When placed after the variable name, the
value of the operand is incremented but the previous value is retained
temporarily until the execution of this statement and it gets updated
before the execution of the next statement.
Syntax:
num++
Example:
1.
a. num = 5
b. num++ = 6
c. Pre-increment operator: When placed before the variable name, the operand’s
value is incremented instantly.
Syntax:
++num
Example:
num = 5
++num = 6
import java.io.*;
class Increment {
// initializing variables
int num = 5;
// increment to 6
System.out.println("Post "
// then printed
System.out.println("Pre "
}}
2. Output:
3. Post increment = 5
4. Pre increment = 7
5. Decrement(–): This is also a unary operator that acts on one operand. It is used to
decrement the value of an integer. It can be used in two ways:
a. Post-decrement operator: When placed after the variable name, the value of
the operand is decremented but the previous values is retained temporarily
until the execution of this statement and it gets updated before the execution
of the next statement.
Syntax:
num--
Example:
num = 5
num-- = 4
b. Pre-decrement operator: When placed before the variable name, the operand’s
value is decremented instantly.
Syntax:
--num
Example:
num = 5
--num = 4
import java.io.*;
class Decrement {
// initializing variables
int num = 5;
// decremented to 4
System.out.println("Pre "
}}
6. Output:
7. Post decrement = 5
8. num = 4
9. Pre decrement = 3
Assignment Operators
These operators are used to assign values to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data-type of the operand on the left
side otherwise the compiler will raise an error. This means that the assignment operators
have right to left associativity, i.e value given on the right-hand side of the operator is
assigned to the variable on the left and therefore right-hand side value must be declared
before using it or should be a constant. The general format of assignment operator is,
variable operator value;
Let’s look at each of the assignment operators and how they operate:
1. “=”: This is the simplest assignment operator which is used to assign the value on
the right to the variable on the left. This is the basic definition of assignment
operator and how does it functions.
Syntax:
num1 = num2;
Example:
a = 10;
ch = 'y';
import java.io.*;
class Assignment {
// Declaring variables
int num;
String name;
// Assigning values
num = 10;
name = "GeeksforGeeks";
}}
Output:
num is assigned: 10
name is assigned: GeeksforGeeks
Note: In many cases, the assignment operators can be combined with other operators to
build a shorter version of the statement called Compound Statement. For example,
instead of a = a+5, we can write a += 5. Let’s look at similar assignment operators that
form the compound statements.
2. “+=”: This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the
current value of the variable on left to the value on the right and then assigning the
result to the operand on the left.
Syntax:
num1 += num2;
Example:
a += 10
This means,
a = a + 10
import java.io.*;
class Assignment {
// Declaring variables
num1 += num2;
Output:
num1 = 10
num2 = 20
num1 = 30
1. 30
2.
3. “-=”: This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting
the value of the variable on right from the current value of the variable on the left and
then assigning the result to the operand on the left.
Syntax:
num1 -= num2;
Example:
a -= 10
This means,
a = a - 10
import java.io.*;
class Assignment {
// Declaring variables
num1 -= num2;
}}
Output:
num1 = 10
num2 = 20
num1 = -10
4. “*=”: This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying
the current value of the variable on left to the value on the right and then assigning the
result to the operand on the left.
Syntax:
num1 *= num2;
Example:
a *= 10
This means,
a = a * 10
import java.io.*;
class Assignment {
// Declaring variables
num1 *= num2;
Output:
num1 = 10
num2 = 20
num1 = 200
5. “/=”: This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the
current value of the variable on left by the value on the right and then assigning the
quotient to the operand on the left.
Syntax:
num1 /= num2;
Example:
a /= 10
This means,
a = a / 10
// Java code to illustrate "/="
import java.io.*;
class Assignment {
// Declaring variables
num1 /= num2;
Output:
num1 = 20
num2 = 10
num1 = 2
6. “%=”: This operator is a compound of ‘%’ and ‘=’ operators. It operates by
dividing the current value of the variable on left by the value on the right and
then assigning the remainder to the operand on the left.
Syntax:
num1 %= num2;
Example:
a %= 3
This means,
a=a%3
import java.io.*;
class Assignment {
// Declaring variables
num1 %= num2;
Output:
num1 = 5
num2 = 3
num1 = 2
import java.io.*;
class Unary {
// variable declaration
int n1 = 20;
n1 = -n1;
}}
Output:
Number = 20
Result = -20
2. ‘NOT’ Operator(!): This is used to convert true to false or vice versa. Basically it
reverses the logical state of an operand.
Syntax:
!(operand)
Example:
cond = !true;
import java.io.*;
class Unary {
// initializing variables
int a = 10, b = 1;
// Displaying cond, a, b
}
}
Output:
1. Cond is: true
2. Var1 = 10
3. Var2 = 1
4. Now cond is: false
5. ! (a < b) = true
6. ! (a > b) = false
7.
8. Increment (++): It is used to increment the value of an integer. It can be used in
two separate ways:
a. Post-increment operator: When placed after the variable name, the value of the
operand is incremented but the previous value is retained temporarily until the
execution of this statement and it gets updated before the execution of the next
statement.
Syntax:
num++
Example:
num = 5
num++ = 6
b. Pre-increment operator: When placed before the variable name, the operand’s
value is incremented instantly.
Syntax:
++num
Example:
num = 5
++num = 6
import java.io.*;
class Unary {
int num = 5;
// increment to 6
System.out.println("Post "
// then printed
System.out.println("Pre "
}}
9. Output:
Post increment = 5
Pre increment = 7
10. Decrement (--): It is used to decrement the value of an integer. It can be used in
two separate ways:
a. Post-decrement operator: When placed after the variable name, the value of the
operand is decremented but the previous values is retained temporarily until the
execution of this statement and it gets updated before the execution of the next
statement.
Syntax:
num--
Example:
num = 5
num-- = 4
b. Pre-decrement operator: When placed before the variable name, the operand’s
value is decremented instantly.
Syntax:
--num
Example:
num = 5
--num = 4
11. Below is the program to illustrate Java unary Decrement(--) operator.
import java.io.*;
class Unary {
// initializing variables
int num = 5;
// decremented to 4
System.out.println("Post "
// then printed
System.out.println("Pre "
}}
Output:
Post decrement = 5
num = 4
Pre decrement = 3
import java.io.*;
class Unary {
// variable declaration
int n1 = 6, n2 = -2;
// Displaying numbers
}}
Output:
First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1
Java Relational Operators with Examples
Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to perform
various calculations and functions be it logical, arithmetic, relational, etc. They are
classified based on the functionality they provide.
Types of Operators:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
Relational Operators are a bunch of binary operators that are used to check for
relations between two operands including equality, greater than, less than, etc. They
return a Boolean result after the comparison and are extensively used in looping
statements as well as conditional if-else statements and so on. The general format of
representing relational operator is:
Syntax:
import java.io.*;
// Main class
class GFG {
// Main driver method
// Initializing variables
+ (var1 == var2));
+ (var1 == var3));
}}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true
Operator 2: ‘Not equal to’ Operator (!=)
This operator is used to check whether the two given operands are equal or not. It
functions opposite to that of the equal-to-operator. It returns true if the operand at
the left-hand side is not equal to the right-hand side, else false.
Syntax:
var1!= var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
var1 != var2 results in true
Example
import java.io.*;
// Main class
class GFG {
// Initializing variables
+ (var1 != var2));
+ (var1 != var3));
}}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: true
var1 == var3: false
Operator 3: Greater than’ operator(>)
This checks whether the first operand is greater than the second operand or not. The
operator returns true when the operand at the left-hand side is greater than the right-
hand side.
Syntax:
var1 > var2
Illustration:
var1 = 30
var2 = 20
var1 > var2 results in true
Example:
import java.io.*;
// Main class
class GFG {
// Initializing variables
}}
Output
Var1 = 30
Var2 = 20
Var3 = 5
var1 > var2: true
var3 > var1: false
Operator 4: Less than’ Operator(<)
This checks whether the first operand is less than the second operand or not. The operator
returns true when the operand at the left-hand side is less than the right-hand side. It
functions opposite to that of the greater-than operator.
Syntax:
var1 < var2
Illustration:
var1 = 10
var2 = 20
var1 < var2 results in true
import java.io.*;
// Main class
class GFG {
// Initializing variables
}}
Output
Var1 = 10
Var2 = 20
Var3 = 5
var1 < var2: true
var2 < var3: false
Operator 5: Greater than or equal to (>=)
This checks whether the first operand is greater than or equal to the second operand or not.
The operator returns true when the operand at the left-hand side is greater than or equal to
the right-hand side.
Syntax:
// Operator
import java.io.*;
// Main class
class GFG {
// Main driver method
// Initializing variables
}}
Output
Var1 = 20
Var2 = 20
Var3 = 10
var1 >= var2: true
var2 >= var3: false
Operator 6: Less than or equal to (<=)
This checks whether the first operand is less than or equal to the second operand or not. The
operator returns true when the operand at the left-hand side is less than or equal to the right-
hand side.
Syntax:
var1 <= var2
Illustration:
var1 = 10
var2 = 10
var3 = 9
var1 <= var2 results in true
var2 <= var3 results in false
Example:
import java.io.*;
// Main class
class GFG {
// Initializing variables
}}
Output
Var1 = 10
Var2 = 10
Var3 = 9
var1 <= var2: true
var2 <= var3: false
import java.io.*;
class Logical {
// initializing variables
// Displaying a, b, c
// two constraints
d = a + b + c;
}
else
System.out.println("False conditions");
}}
Output:
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50
2. 'Logical OR' Operator(||): This operator returns true when one of the two conditions
under consideration are satisfied or are true. If even one of the two yields true, the
operator results true. To make the result false, both the constraints need to return false.
Syntax:
condition1 || condition2
Example:
a = 10, b = 20, c = 20
condition1: a < b
condition2: b > c
if(condition1 || condition2)
d = a+b+c
// logical OR operator
import java.io.*;
class Logical {
// initializing variables
int a = 10, b = 1, c = 10, d = 30;
// Displaying a, b, c
// two constraints
if (a > b || c == d)
System.out.println("One or both"
else
System.out.println("Both the"
Output:
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both the conditions are true
3. 'Logical NOT' Operator(!): Unlike the previous two, this is a unary operator and returns
true when the condition under consideration is not satisfied or is a false condition.
Basically, if the condition is false, the operation returns true and when the condition is
true, the operation returns false.
Syntax:
!(condition)
Example:
a = 10, b = 20
import java.io.*;
class Logical {
// initializing variables
int a = 10, b = 1;
// Displaying a, b, c
}}
Output:
Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
This article explains all that one needs to know regarding the Ternary Operator.
Ternary Operator
Java ternary operator is the only conditional operator that takes three operands. It’s a
one-liner replacement for if-then-else statement and used a lot in Java programming.
We can use the ternary operator in place of if-else conditions or even switch
conditions using nested ternary operators. Although it follows the same algorithm as
of if-else statement, the conditional operator takes less space and helps to write the if-
else statements in the shortest way possible.
Syntax:
if(Expression1){
variable = Expression2;
}
else{
variable = Expression3;
}
Example:
num1 = 10;
num2 = 20;
res=(num1>num2)? (num1+num2):(num1-num2)
Since num1<num2,
the second operation is performed
res = num1-num2 = -10
Flowchart of Ternary Operation
Example 1:
import java.io.*;
class Ternary {
// variable declaration
}}
Output:
First num: 5
Second num: 10
Maximum is = 10
Example 2:
import java.io.*;
class Ternary {
// variable declaration
}}
Output:
First num: 5
Second num: 10
Result = -5
// bitwise operators
// Initial values
int a = 5;
int b = 7;
// bitwise and
// bitwise or
// 0101 | 0111=0111 = 7
// bitwise xor
// 0101 ^ 0111=0010 = 2
// bitwise not
// ~0101=1010
// assignment
// a=a&b
a &= b;
Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Shift Operators: These operators are used to shift the bits of a number left or right thereby
multiplying or dividing the number by two respectively. They can be used when we have to
multiply or divide a number by two. General format:
number shift_op number_of_places_to_shift;
Signed Right shift operator (>>) –
Shifts the bits of the number to the right and fills the voids left with the sign bit (1 in case
of negative number and 0 in case of positive number). The leftmost bit and a depends on
the sign of initial number. Similar effect as of dividing the number with some power of
two.
For example,
Example 1:
a = 10
a>>1 = 5
Example 2:
a = -10
a>>1 = -5
We preserve the sign bit.
Unsigned Right shift operator (>>>) –
Shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost
bit is set to 0. (>>>) is unsigned-shift; it’ll insert 0. (>>) is signed, and will extend the
sign bit.
For example,
Example 1:
a = 10
a>>>1 = 5
Example 2:
a = -10
a>>>1 = 2147483643
DOES NOT preserve the sign bit.
Left shift operator (<<) –
Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar
effect as of multiplying the number with some power of two.
For example,
a = 5 = 0000 0101
b = -10 = 1111 0110
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
// shift operators
int a = 5;
int b = -10;
// similar to 5*(2^2)
// similar to 5/(2^2)
}}
Output
a<<2 = 20
b>>2 = -3
b>>>2 = 1073741821
1. AND && OR ||
int x, y; // && = AND This is a shorthand
y = -10; // So, it first checks the condition on the left, if satisfied, then
checks on the right-hand side.
Output: 20
Output:
10
10.0
1.
public class Simple{
2.
public static void main(String[] args){
3.
float f=10.5f;
4.
//int a=f;//Compile time error
5.
int a=(int)f;
6.
System.out.println(f);
7.
System.out.println(a);
}
}
Output:
10
10.0
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Output:
10
12
12
10
Output:
22
21
Output:
-11
false
true
}}
Output:
15
50
Output:
21
Output:
40
80
80
240
Output:
2
-5
1073741819
The bitwise & operator always checks both conditions whether first condition is
true or false.
Output:
false
false
Output:
false
10
false
11
The bitwise | operator always checks both conditions whether first condition is
true or false.
Output:
true
true
true
10
true
11
Output:
Another Example:
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }
8. }
Output:
Output:
14
16
Output:
13
18
Adding short
Output:
Compile time error
Output: 20
the operator
- (Subtraction)
Subtracts right-hand operand from left-hand operand
2
Example: A - B will give -10
* (Multiplication)
Multiplies values on either side of the operator
3
Example: A * B will give 200
/ (Division)
Divides left-hand operand by right-hand operand
4
Example: B / A will give 2
% (Modulus)
Divides left-hand operand by right-hand operand and returns remainder
5
Example: B % A will give 0
++ (Increment)
Example
The following program is a simple example which demonstrates the arithmetic operators.
Copy and paste the following Java program in Test.java file, and compile and run this
program:
a + b = 30
- b = -10
* b = 200
/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27
== (equal to)
Checks if the values of two operands are equal or not, if yes then condition
1 becomes true.
Checks if the values of two operands are equal or not, if values are not
2 equal then condition becomes true.
Example: (A != B) is true.
> (greater than)
Checks if the value of left operand is greater than the value of right
operand, if yes then condition becomes true.
Example
The following program is a simple example that demonstrates the relational operators. Copy
and paste the following Java program in Test.java file and compile and run this program.
a == b = false
a! = b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
| (bitwise or)
Binary OR Operator copies a bit if it exists in either operand.
2
Example: (A | B) will give 61 which is 0011 1101
^ (bitwise XOR)
Binary XOR Operator copies the bit if it is set in one operand but not
both.
3
Example: (A ^ B) will give 49 which is 0011 0001
~ (bitwise compliment)
Binary Ones Complement Operator is unary and has the effect of 'flipping'
4 bits.
Example: (~A) will give -61 which is 1100 0011 in 2's complement form due to a
signed binary number.
6 Binary Right Shift Operator. The left operands value is moved right
by the number of bits specified by the right operand.
c = a & b; /* 12 = 00001100 */
System.out.println("a &b=" +c );
c = a | b; /* 61 = 00111101 */
System.out.println("a |b=" +c );
c = a ^ b; /* 49 = 00110001 */
System.out.println("a ^b=" +c );
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 15
a >>> 15
Operator Description
|| (logical or)
Called Logical OR Operator. If any of the two operands are non-zero, then
2
the condition becomes true.
Example: (A || B) is true.
! (logical not)
Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true then Logical NOT operator will make false.
a && b = false
a || b = true
!(a && b) = true
=
1
Simple assignment operator. Assigns values from right side operands to left
side operand.
Example: C += A is equivalent to C = C + A
-=
Subtract AND assignment operator. It subtracts right operand from
the left operand and assign the result to left operand.
Example:C -= A is equivalent to C = C – A
*=
Multiply AND assignment operator. It multiplies right operand with
the left operand and assign the result to left operand.
Example: C *= A is equivalent to C = C * A
/=
Divide AND assignment operator. It divides left operand with the
right operand and assign the result to left operand.
Example: C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator. It takes modulus using two
operands and assign the result to left operand.
Example: C %= A is equivalent to C = C % A
<<=
Left shift AND assignment operator.
>>=
Right shift AND assignment operator
54
Java
&=
Bitwise AND assignment operator.
^=
bitwise exclusive OR and assignment operator.
Example: C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and assignment operator.
Example: C |= 2 is same as C = C | 2
Example
The following program is a simple example that demonstrates the assignment operators.
Copy and paste the following Java program in Test.java file. Compile and run this program:
c += a;
System.out.println("c += a = " + c);
c -= a;
System.out.println("c -= a = " + c);
c *= a;
System.out.println("c *= a = " + c);
a = 10;
c = 15;
c /= a;
System.out.println("c /= a = " + c);
a = 10;
c = 15;
c %= a;
System.out.println("c %= a = " + c);
c <<= 2;
System.out.println("c <<= 2 = " + c);
c >>= 2;
System.out.println("c >>= 2 = " + c);
c >>= 2;
System.out.println("c >>= a = " + c);
c &= a;
System.out.println("c &= 2 = " + c);
c ^= a;
c |= a;
System.out.println("c |= a
= " + c);
}}
c = a + b = 30
c += a = 40
56
Java
c /= a = 1
c %= a =5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a =0
c ^= a = 10
c |= a = 10
Miscellaneous Operators
There are few other operators supported by Java Language.
Following is an example:
Value of b is: 30
Value of b is: 20
Instance of Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as:
If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is an example:
true
This operator will still return true, if the object being compared is the assignment compatible
with the type on the right. Following is one more example:
class Vehicle {}
true
Java
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
= += -= *= /= %= >>= <<=
Assignment &= ^= |= Right to left
2. USING OPERATORS IN JAVA
public class{
public static void main(String []args){
java.util.Scanner scan = new java.util.Scanner(System.in);
int x,y;
System.out.println("Enter your first value: ");
x=scan.nextInt();
System.out.println("Enter your second value: ");
y=scan.nextInt();
int result=(x+y);
System.out.println("This is the result" +result);
System.out.println("Enter the operators ");
String operation=scan.next();
if(operation.equals("+")){
System.out.println("This is the addition result" +(x+y));
}else if(operation.equals("-")){
System.out.println("This is the subtraction result" +(x-y));
}else if(operation.equals("*")){
System.out.println("This is the multiplication result" +(x*y));
}else if(operation.equals("/")){
System.out.println("This is the division result" +(x/y));
}else
System.out.println("Enter the correct operation: ");
}}
7. MATHEMATICS OPERATION
Absolute Value
class AbsValue{
public static void main(String[]args){
double a= -33.65;
int b=185;
system.out.println("Absolute value of a: "+Math.abs(a));
system.out.println("Absolute value of b: "+Math.abs(b));
}}