Java Operators
In this lesson you are going to learn about operators in Java and also what are the different types of operators used in Java programming.
In our previous lesson we have learnt how to take user input in Java. We were performing different types of arithmetic operations in order to create a simple ration shop billing application which took different values as the user input and calculated total billing amount.
During the
programming the billing application we used different signs like addition (+), multiplication (*) etc. These signs are called operators in Java
programming.
Types of
Operators in Java
There are five types of operators in Java.
- Arithmetic Operators
- Bitwise Operators
- Assignment Operators
- Comparison Operators
- Logical Operators
1.Java Arithmetic
Operators
Arithmetic operators are used to
perform mathematical operations such addition, division, multiplication,
subtraction and modulation.
Let’s see the example of arithmetic operators in
below:
package operators; |
public class ArithmeticOperators { public static void main(String[] args) { int x = 50; int y = 100; int z = x + y; System.out.println(z); } } |
In the above example we have simply
created two variables called x and y and also we have initiated them with some
value.
Then we have applied the plus (+) operator which is an arithmetic operator in java. The plus
operator helped in adding up to values.
The third variable (z) has been
initiated with the sum of variable x and y.
So, we can understand the plus (+) symbol is working here as an operator in Java.
Similarly we may use other arithmetic
operators and perform some more complex operations.
List of all arithmetic
operators in Java:
Operators Symbol |
Operators Used for |
+ |
For addition operations |
- |
For subtraction operations |
* |
For Multiplication operations |
/ |
For Division operations |
% |
For Modulation operations |
++ |
For Increment operations |
-- |
For Decrement operations |
The output in the console:
It is quite easy to under the
operations of addition, subtraction, multiplication and divisional operators.
Modulus operator in Java:
Modulus operator performs the modulus
operation between two numbers.
The remainder value of a divisional
operation is returned by the modulus operator.
Let’s suppose we divide 10 by 3. Here
the remainder we get is 1. That is exactly what is returned by a modulus
operator.
Example of modulus operator in Java
Programming:
package operators; import java.util.Scanner; public class
ArithmeticOperators { public static void main(String[] args) { int a = 20; int b = 6; int c = a % b; System.out.println(c); } } |
Output in the
Console: 2 |
Increment and decrement operator in Java:
In Java programming ++ symbol is known as increment operator and – – symbol is known as decrement operator.
As the names suggest these operators increase
(++) or decrease (– –) the values of a variables by 1.
You can apply these operators in two
different ways as prefix or post-fix.
When you apply these operators before
the variable name (++var) it
is called using as prefix.
Similarly, applying these operators
after the variable name (var++), is called
using as post-fix.
What is the difference between prefix and
post-fix of increment or decrement operators in Java?
When you use these operators as
post-fix, it returns the original value of the variable first, then the
increment or decrement operation is taken place.
Whereas, when you apply increment and
decrement operators as prefix, it performs the increment or decrement operation
on the variable first and then the incremented or decremented values of those
variables are returned.
Example of Increment and Decrement Operators in Java:
package operators; public class
ArithmeticOperators { public static void main(String[] args) { int a = 10; |
// Original
Value System.out.println(a); // Increment operator applied as postfix
but it returned the same old value. System.out.println(a++); // Incremented
value of a is returned. System.out.println(a); // Increment operator applied as prefix System.out.println(++a); } } |
Output in the Console: 10 10 11 12 |
2. Java Bitwise
Operators
Unlike arithmetic operators, bitwise operators do not perform
operations on integer values.
The bits of the decimal numbers are the actual operands of bitwise operators. These operators perform their operations at the bit level only.
The binary 0 and 1, which are the machine readable language, get affected and manipulated through these bitwise operations.
Different bitwise operators are:
1. Bitwise
OR Operator (Denoted by ‘|’) 2. Bitwise
AND Operator (Denoted by ‘&’) 3. Bitwise
XOR Operator (Denoted by ‘^’) 4. Bitwise
Complement (Denoted by ‘~’) 5. Left
shift Operator (‘<<’) 6. Signed
Right Shift Operator (‘>>’) 7. Unsigned
Right Shift Operator (‘>>>’) |
Bitwise OR
Operator in Java:
Java
bitwise OR operator performs OR operation on the bit
level of given integer values. This operation return 1 if either of the bit
level operands is 1 or else it returns 0.
Bitwise OR operator is denoted by symbol ‘|’.
The true table of bitwise OR Operator is given below:
a |
b |
a | b |
1 |
0 |
1 |
0 |
1 |
1 |
0 |
0 |
0 |
1 |
1 |
1 |
Here are the given 2 integer numbers
used to perform bitwise OR operation.
Let’s
take 2 integers 5 & 6. Binary
Representation of Number 5 is = 0101 Binary
Representation of Number 6 is = 0110 Bitwise
OR operation 0101 | 0110 ------------------- 0111
------------------- Decimal representation
of 0111 is 7. |
|
Let’s also see how the programming codes
look like if we have to perform bitwise
OR operation on two given integers.
package operators; public class BitwiseOrOperator
{ public static void main(String[] args) { int a = 5; int b = 6; int bitwise_or; bitwise_or = a | b; System.out.println(bitwise_or); } } |
Output in the
Console: 7 |
Bitwise AND operator in Java:
Bitwise
AND operator in Java performs AND operation on the bit
level of given integer values. This operation return 1 only if both the bit
level operands are 1 or else it returns 0.
Bitwise AND operator is denoted by symbol ‘&’.
The true table of bitwise AND Operator is given below:
a |
b |
a & b |
1 |
0 |
0 |
0 |
1 |
0 |
0 |
0 |
0 |
1 |
1 |
1 |
Let’s
take 2 integers 8 & 9 Binary
Representation of Number 8 is = 1000 Binary
Representation of Number 9 is = 1001 Bitwise AND
operation 1000 | 1001 ------------------- 1000
------------------- Decimal representation
of 1000 is 8 |
|
Let’s also see how the programming
codes look like if we have to perform bitwise
AND operation on two given integers.
package operators; public class BitwiseAndOperator
{ public static void main(String[] args) { int a = 8; int b = 9; int Bitwise_And_Operator; Bitwise_And_Operator = a&b; System.out.println(Bitwise_And_Operator); } } |
Output in the
Console: 8 |
Bitwise XOR Operator
in Java:
Bitwise XOR operator in Java performs XOR operation on the bit level of given integer values. This operation return 1 if only one of the bit level operands is 1 or else it returns 0.If both the operands are 1 or 0 then the return value will be 0 only.
Bitwise XOR operator is denoted by symbol ‘^’.
a |
b |
a ^ b |
1 |
0 |
1 |
0 |
1 |
1 |
0 |
0 |
0 |
1 |
1 |
0 |
Here are the given 2 integer numbers
used to perform bitwise XOR operation.
Let’s
take 2 integers 3 & 4 Binary
Representation of Number 3 is = 0011 Binary
Representation of Number 4 is = 0100 Bitwise XOR
operation 0011 | 0100 ------------------- 0111
------------------- Decimal representation
of 0111 is 7 |
|
Let’s also see how the programming
codes look like if we have to perform bitwise
XOR operation on two given integers.
package operators; public class BitwiseXor { public static void main(String[] args) { int a = 3; int b = 4; int BitwiseXor = a^b; System.out.println(BitwiseXor); } |
Output in the
Console: 7 |
Bitwise Complement Operator in Java:
Bitwise
complement operator in Java performs bitwise complement
operation at the bit level on a single integer value. This is also called a
unary operator.
This operation returns 1 if the operand is 0 and returns 0 if the operand is 1.
Bitwise complement operator is denoted by symbol ‘~’.
The true table of bitwise complement operator is given below:
Let’s
take one integers 12 Binary
Representation of Number 12 is = 1100 Bitwise complement
operation ~ 1100 ------------------- 0011
------------------- Decimal representation
of 0011 is 3 But, compiler will return -13 as a
result. |
|
Let’s understand why the compiler will give a result of 13 in above case.
If
you do this calculation the other way round calculating 2’scomplement of 13 (i.e.
-13), it will be equivalent to the
bitwise complement of 12.
So,
now it is proved that bitwise complement of 12 is -13.
Note: If we
make a binary addition of +1 to the bitwise complement of 13, we get the 2’s
complement of 13 (i.e. -13) |
Let’s also see how the programming
codes look like if we have to perform bitwise
complement operation on an integer.
package operators; public class BitwiseComplement
{ public static void main(String[] args) { int a = 12; int BitwiseComplement = ~a;
System.out.println(BitwiseComplement); } } |
Output in the
Console: -13 |
Shift Operators
in Java:
Now we discuss about Java shift operators. Here we are going to enlighten on three Shift operators.
- Left shift Operator (‘<<’)
- Signed Right Shift Operator (‘>>’)
- Unsigned Right Shift Operator (‘>>>’)
Java Left shift Operator (‘<<’):
Left shift operator is a unary
operator which performs operation on bit level of a single integer number.
It shifts each bits of an integer
towards the left side by a certain number of specified bits.
Left shift operator is denoted by “<<” symbol.
After the left shift operation, the left most bit will be discarded. As 1 bit
is being discarded here so there will be a vacancy at the right most field
which will be fulfilled by 0s.
Java Right shift Operator (‘>>’):
Right shift operator is just opposite operation of left shift
operator which performs operation on bit level of a single integer number.
It shifts each bits of an integer
towards the right side by a certain
number of specified bits.
Right shift operator is denoted by “>>” symbol.
In the above image we have shown the
operation of right shift operator.
In the above image, the right shift operator pushes each bit to the right by
1-bit.
After the right shift operation, the right most bit will be discarded. As 1
bit is being discarded here so there will be a vacancy at the left most field
which will be fulfilled by 0s.
Note: Every 1-bit
left shift operation, will double the integer value. Similarly every 1-bit
right shift operation will divide the integer value by 2. |
Let’s see some programming based on
left & right shift operations.
package operators; public class ShiftOperator { public static void main(String[] args) { System.out.println("-------LEFT
SHIFT OPERATION--------"); int a = 10; int Left_Shift_Operation = a << 1; System.out.println(Left_Shift_Operation); Left_Shift_Operation = a << 2; System.out.println(Left_Shift_Operation); Left_Shift_Operation = a << 3; System.out.println(Left_Shift_Operation); System.out.println("-------RIGHT
SHIFT OPERATION---------"); int b = 80; int Right_Shift_Operation = b >> 1; System.out.println(Right_Shift_Operation); Right_Shift_Operation = b >> 2; System.out.println(Right_Shift_Operation); Right_Shift_Operation = b >> 3; System.out.println(Right_Shift_Operation); } } |
Output in the console: -------LEFT SHIFT OPERATION-------- 20 40 80 -------RIGHT SHIFT OPERATION--------- 40 20 10 |
Java Unsigned Right Shift Operator
(‘>>>’):
There is an unsigned right shift
operator also in Java which is denoted by ‘>>>’.Unlike
signed right shift operator, it does not assign the sign bit at the leftmost
position.
The unsigned right shift operator assigns
0 at the leftmost position whereas the right shift operator assigns the
sign-bit at the leftmost position.
3. Java Assignment
Operators:
Assignment operators are used to
perform assignment operations on the variables.
Let’s take an example x = 15, here x is a variable and ‘=’ is an
assignment operator. This operator is assigning the value (15) to the
variable x.
Let’s see a programming example based
on assignment operator.
package operators; public class
assignment_operators { public static void main(String[] args) { int a = 20; int b = 40; int c = a*b; System.out.println(c); } } |
Output
in the console: 800 |
List of assignment operators in Java:
Operators |
Assignment Operations |
Elaboration |
= |
x = 20 |
x = 20 |
+= |
x += 20 |
x = x + 20 |
*= |
x *= 20 |
x = x * 20 |
-= |
x -= 20 |
x = x - 20 |
/= |
x /= 20 |
x = x / 20 |
%= |
x %= 2 |
x = x % 2 |
If you notice carefully, you will observe all
the arithmetic operators have been used in above table with ‘=’ sign to form an assignment operator.
Similarly, you can use all the bitwise
operators along with ‘=’ sign to make a new
assignment operator. For example x >>=5 which is equivalent to x = x >> 5
Java programming using assignment operators:
package operators; public class
assignment_operators { public static void main(String[] args) { int a=10; int b=40; int c=2; int d=40; int e=10; a+=20; b-=20; c*=20; d/=20; e%=20; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); System.out.println(e); } } |
Output in the Console: 30 20 40 2 10 |
4. Java Comparison
Operators
The comparison operators in Java are used to make comparison between two
variables.
List
of comparison operators in Java:
Operator Symbol |
Operator Known as |
Example |
== |
Equal to Operator |
a == b |
!= |
Not Equal to Operator |
a != b |
< |
Less than Operator |
a < b |
> |
Greater than Operator |
a > b |
<= |
Less than Equal to Operator |
a <= b |
>= |
Greater than Equal to Operator |
a >= b |
Java
Equal to Operator (==):
This operator is used in Java
programming to ascertain whether the values inside two different variables are
equal.
If the two variables hold equal
values, this operator returns true or else it returns false.
package operators; import java.util.Scanner; public class
comparison_operators { public static void main(String[] args) { int x; int y; boolean result; Scanner
sc = new Scanner(System.in); System.out.println("Enter the
value of Variable-1 :"); x=sc.nextInt(); System.out.println("Enter the
value of Variable-2 :"); y=sc.nextInt(); result = x==y; if(result==true) { System.out.println("Variable-1
and Variable-2 are equal."); }else { System.out.println("Variable-1
and Variable-2 are not equal."); } } } |
Output in the
Console: Enter the value of Variable-1 : 30 Enter the value of Variable-2 : 30 Variable-1 and Variable-2 are equal. |
Java
Not Equal to Operator (!=):
This operator is used in Java
programming to ascertain whether the values inside two different variables are
not equal.
If the two variables hold different
values, this operator returns true or else it returns false.
package operators; import java.util.Scanner; public class
comparison_operators { public static void main(String[] args) { int x; int y; boolean result; Scanner
sc = new Scanner(System.in); System.out.println("Enter the
value of Variable-1 :"); x=sc.nextInt(); System.out.println("Enter the
value of Variable-2 :"); y=sc.nextInt(); result = x!=y; if(result!=true) { System.out.println("Variable-1
and Variable-2 are equal."); }else { System.out.println("Variable-1
and Variable-2 are not equal."); } } } |
Output in the
Console: Enter the value of Variable-1 : 6 Enter the value of Variable-2 : 7 Variable-1 and Variable-2 are not equal. |
|
Java
Less Than Operator (<):
This operator is used in Java
programming to ascertain whether the value inside the left hand side variable
is less than the value inside the right hand side variable.
If the above condition matches, this
operator returns true or else it returns false.
package operators; import java.util.Scanner; public class
comparison_operators { public static void main(String[] args) { int x; int y; boolean result; Scanner
sc = new Scanner(System.in); System.out.println("Enter the
value of Variable-1 :"); x=sc.nextInt(); System.out.println("Enter the
value of Variable-2 :"); y=sc.nextInt(); result = x<y; if(result==true) { System.out.println("Variable-1 is
less than Variable-2"); }else { System.out.println("Variable-1 is
not less than Variable-2."); } } } |
Output in the
Console: Enter the value of Variable-1 : 6 Enter the value of Variable-2 : 7 Variable-1 is less than Variable-2. |
|
Java
Greater Than Operator (>):
This operator is used in Java
programming to ascertain whether the value inside the left hand side variable
is greater than the value inside the right hand side variable.
If the above condition matches, this
operator returns true or else it returns false.
package operators; import java.util.Scanner; public class
comparison_operators { public static void main(String[] args) { int x; int y; boolean result; Scanner
sc = new Scanner(System.in); System.out.println("Enter the
value of Variable-1 :"); x=sc.nextInt(); System.out.println("Enter the
value of Variable-2 :"); y=sc.nextInt(); result = x>y; if(result==true) { System.out.println("Variable-1 is
greater than Variable-2"); }else { System.out.println("Variable-1 is
not greater than Variable-2."); } } } |
Output in the
Console: Enter the value of Variable-1 : 7 Enter the value of Variable-2 : 6 Variable-1 is greater than Variable-2. |
|
Java
Less Than Equal to Operator (<=):
This operator is used in Java
programming to ascertain whether the value inside the left hand side variable
is less than or equal to the value inside the right hand side variable.
If the above condition matches, this
operator returns true or else it returns false.
package operators; import java.util.Scanner; public class
comparison_operators { public static void main(String[] args) { int x; int y; boolean result; Scanner
sc = new Scanner(System.in); System.out.println("Enter the
value of Variable-1 :"); x=sc.nextInt(); System.out.println("Enter the
value of Variable-2 :"); y=sc.nextInt(); result = x<=y; if(result==true) { System.out.println("Variable-1 is
less than or equal to Variable-2."); }else { System.out.println("Variable-1 is
not less than or equal to Variable-2."); } } } |
Output in the
Console (Example 1): Enter the value of Variable-1 : 4 Enter the value of Variable-2 : 4 Variable-1 is less than or equal to
Variable-2. Output in
the Console (Example 2): Enter the value of Variable-1 : 1 Enter the value of Variable-2 : 3 Variable-1 is less than or equal to
Variable-2. |
|
|
Java
Greater Than Equal to Operator (>=):
This operator is used in Java
programming to ascertain whether the value inside the left hand side variable
is greater than or equal to the value inside the right hand side variable.
If the above condition matches, this
operator returns true or else it returns false.
package operators; import java.util.Scanner; public class
comparison_operators { public static void main(String[] args) { int x; int y; boolean result; Scanner
sc = new Scanner(System.in); System.out.println("Enter the
value of Variable-1 :"); x=sc.nextInt(); System.out.println("Enter the
value of Variable-2 :"); y=sc.nextInt(); result = x>=y; if(result==true) { System.out.println("Variable-1 is
greater than or equal to Variable-2."); }else { System.out.println("Variable-1 is
not greater than or equal to Variable-2."); } } } |
Output in the
Console (Example 1): Enter the value of Variable-1 : 4 Enter the value of Variable-2 : 4 Variable-1 is greater than or equal to
Variable-2. Output in the
Console (Example 2): Enter the value of
Variable-1 : 5 Enter the value of
Variable-2 : 3 Variable-1 is greater
than or equal to Variable-2. |
|
|
5. Java Logical
Operators
Logical operators are used in decision
making in Java programming.
Suppose we take an example 5 > 3. Similarly, we take
another example 10<20.
Now if we have to perform an operation where we have to ascertain if both the
expressions are true or they are false or may be either of the expressions is
true.
In order to perform these separate
operations we would be requiring the help of Java logical operators.
List
of logical operators in Java:
Operator Name |
Operator |
Details |
Logical and Operator |
&& |
This operator returns true value if both the expressions are
true |
Logical or operator |
|| |
This operator returns true value if any one of the expressions is true |
Logical not operator |
! |
This operator returns the opposite value. If the expressions
return true this operator will convert it to false and vice versa. |
Programming of Java logical operator:
|
package operators; import java.util.Scanner; public class logical_operator { public static void main(String[] args) { int age; int score; boolean status; Scanner sc = new Scanner(System.in); System.out.println("Note: You
can participate only if your age is greater than or equal to 12 and your
score is greater than 15."); System.out.println("==========================================================================================================="); System.out.println("Enter Your
Age:"); age = sc.nextInt(); System.out.println("Enter Your
score:"); score = sc.nextInt(); if(age>=12 && score>15) { System.out.println("You are
eligible to participate."); }else { System.out.println("You are not
eligible to participate."); } } } |
|
Output in the Console: Note: You can
participate only if your age is greater than or equal to 12 and your score is
greater than 15. =========================================================================================================== Enter Your Age: 12 Enter Your score: 17 You are eligible to
participate. |
Precedence of Java Operator:
Java operator precedence sets an order
in which multiple operators if any in an expression are executed to evaluate
the expression.
Let’s consider the below expression.
package operators; public class logical_operator { public static void main(String[] args) { int a = 5; int b = 10; int c = 4; int d; d = a+b*c; System.out.println(d); } } |
In this example, there are two
arithmetic operations used in the expression. What do you think? Which operator
will get the precedence first to get executive?
Is the value of variable ‘d’ going to
be (a+b)*c = 60 or it will be a+(b*c) = 45.
The precedence of multiplication
operator (*) has got the higher precedence than the addition operator (+).
Hence the multiplication operation will be executive first and then the
addition operation will take place.
So, it is quite clear to us that every
java operators are having a particular precedence.
Java Operator Precedence Table:
Java operator precedence table lists out
all the java operators in such an order that operators having higher precedence
appear towards the top end of the table and the lower precedence operators
appear towards the bottom of the table.
Operator
category |
Operator |
Postfix (Unary Operators) |
++
-- |
Prefix (Unary Operators) |
++
-- + -
~ ! |
Multiplicative (Arithmetic
Operators) |
*
/ % |
Additive (Arithmetic Operators) |
+
- |
Shift Operators |
<< >>
>>> |
Relational (Comparative operators) |
<
> <= >=
instanceof |
Relational (Equality) |
==
!= |
Bitwise AND operator |
& |
Bitwise XOR operator |
^ |
Bitwise OR operator |
| |
Logical AND operator |
&& |
Logical OR operator |
|| |
Ternary operator |
? : |
Assignment Operators |
=
+= -= *=
/= %= &=
^= |= <<=
>>= >>>= |
Sum Up:
In this lesson we have discussed about all type of Java operators. We have elaborated the functions of each operators in a detailed manner with adequate example. Please give your valuable feedback about this lesson.
No comments: