An operator is a symbol that tells the compiler to perform a specific mathematical, logical or other manipulation. Java has four general classes of operators.
Arithmetic Operators: The operators that are used to carry out fundamental arithmetic operations are called arithmetic operators. The following table shows complete set of arithmetic operators.
S.N | Operator | Meaning |
1 | + | Addition |
2 | – | Subtraction |
3 | * | Multiplication |
4 | / | Division |
5 | % | Modulus |
6 | ++ | Increment |
7 | — | Decrement |
8 | += | Addition Assignment |
9 | -= | Subtraction Assignment |
10 | *= | Multiplication Assignment |
11 | /= | Division Assignment |
12 | %= | Modulus Assignment |
The operands of the arithmetic operators must be of a numeric type. We cannot use them on boolean types, but we can use them on char types since the char in Java is subset of int.
The following program illustrates the use of arithmetic operators.
public class BasicMath{ public static void main(String[] args) { int a = 2; int b = a*3; int c = b/2; int d = c-a; int e = -d; System.out.println("Arithmetic using integers"); System.out.println("a = "+a); System.out.println("b = "+b); System.out.println("c = "+c); System.out.println("d = "+d); System.out.println("e = "+e); System.out.println("Arithmetic using doubles"); double da = 2.00; double db = da*3; double dc = db/4; double dd = dc-a; double de = -dd; System.out.println("da = "+da); System.out.println("db = "+db); System.out.println("dc = "+dc); System.out.println("dd = "+dd); System.out.println("de = "+de); } }
The output of the above program is:
Arithmetic using integers
a = 2
b = 6
c = 3
d = 1
e = -1
Arithmetic using doubles
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5
The Modulus Operator: The modulus operator, %, returns the remainder of a division operation. It can be applied to floating point as well as integer types. The following example program demonstrates the %;
Let us consider the following program
public class Modulus{ public static void main(String[] args) { int x = 42; double y = 42.25; System.out.println("x mod 10 ="+x%10); System.out.println("y mod 10 = "+y%10); } }
The output of the above program is:
x mod 10 =2
y mod 10 = 2.25
Increment and Decrement Operator
The increment operator increases its operand by one. The decrement operator decreases its operand by one. For example, the statement:
x = x+1;
can be rewritten like this by use of the increment operator:
x++;
Similarly , this statement
x = x-1;
is equivalent to
x–;
Let us consider the following program:
public class IncDec{ public static void main(String[] args) { int a = 1; int b = 2; int c; int d; c = ++b; d = a++; c++; System.out.println("a = "+a); System.out.println("b = "+b); System.out.println("c = "+c); System.out.println("d = "+d); } }
The output of the above program is:
a = 2
b = 3
c = 4
d = 1
The Bitwise Operator
Java provides several bitwise operators which can be applied to the integer types, long, int, short, char and byte. These operators act upon the individual bits of their operands.
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^ and ~. The following table shows the output of each operation. The bitwise operators are applied to each individual bit within each
A | B | A|B | A&B | A^B | ~A |
0 | 0 | 0 | 0 | 0 | 1 |
1 | 0 | 0 | 0 | 1 | 0 |
0 | 1 | 0 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 | 1 |
The Bitwise NOT: This is also called bitwise complement. It is a unary operator. It is denoted by the sign ‘~’. It inverts all of the bits if its operand. For example, the number 42 has the following bit pattern:
00101010
becomes 11010101 after the NOT operator is applied.
The Bitwise AND
The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all other cases. Here is an example:
00101010 42
&00001111 15
00001010 10
The Bitwise OR
The OR operator,|, combines bits such that if either of the bits in the operands is a 1, then the resultant bit is a 1. Let us take the above example:
00101010 42
|00001111 15
00101111 47
The Bitwise XOR
The XOR operator, ^, combines the bits such that if exactly one operand is 1, then the result is 1. Otherwise, the result is zero. Let us consider the following program:
00101010 42
^00001111 15
00001111 10
The following program illustrates the bitwise operators.
public class BitLogic { public static void main(String[] args) { String binary[] = {"0000","0001","0010","0011","0100","0101","0110","0111", "1000","1001","1010","1011","1100","1101","1110","1111"}; int a=3; int b = 6; int c = a|b; int d = a&b; int e = a^b; int f = (~a&b)|(a&~b); int g = ~a&0x0f; System.out.println ("a = "+binary[a]); System.out.println ("b = "+binary[b]); System.out.println ("c = "+binary[c]); System.out.println ("d = "+binary[d]); System.out.println ("e = "+binary[e]); System.out.println ("(~a&b)|(a&~b) = "+binary[f]); System.out.println("~a&0x0f = "+binary[g]); } }
The output of the above program is:
a = 0011
b = 0110
c = 0111
d = 0010
e = 0101
(~a&b)|(a&~b) = 0101
~a&0x0f = 1100
The Left Shift
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times. It has the general form:
value<<num
Here, num specifies the number of positions to left-shift the value in value. That is , the<< moves all of the bits in the specified value to the left by the number of bit positions specified by num. For each, shift, the higher order bit is shifted out (and lost), and zero is brought in on the right. This means that when a left shift is applied to an int operand, bits are lost once they are shifted past bit position 31. If the operand is a long, then bits are lost after bit position 63.
Let us consider the following program
public class ByteShift { public static void main (String[] args){ byte a = 64,b; int i; i = a<<2; b = (byte)(a<<2); System.out.println ("Original value of a:"+a); System.out.println ("i and b "+i+" "+b); } }
The output of the above program is:
Original value of a : 64
i and b 256 0
Since a is promoted to int for the purpose of evaluation, left shifting the value 64 (0100 0000) twice results in i containing the value 256 (1 0000 0000). However, the value in b contains 0 because after the shift, the low, order byte is now zero. Its only 1 bit has been shifted out
Let us see one program.
public class ByteShift { public static void main(String[] args){ int i; int num = 0xFFFFFFE; for (i=0;i<6;i++) { num = num<<1; System.out.println (num); } } }
The output of the above program is:
536870908
1073741816
2147483632
-32
Since each bit shift has the effect of doubling the original value, programmers frequently use this fact as an efficient alternative to multiplying by 2. We must be careful while shifting bits. If we shift a 1 bit into the high-order position (bit 31 or 63), the value will become negative.
The Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number of times. Its general form is shown as below:
value>>nums
Here, num specifies the number of positions to right shift the value in value. That is, the >> moves all of the bits in the specified value to the right the number of bits positions specified by num.
The following code fragment shifts the value 32 to the right by two positions, resulting a being set to 8.
int a = 32;
a = a>>2; // a is now 8
When a value has bits that are “shifted off”, those bits are lost.
Let us look on one more example:
00100011 35
>>2
00001000 8
Each time we shift a value to the right; it divides that value by two and discards any remainder. We can take advantage of this for high performance integer division by 2 but we must sure that we are not shifting any bits off the right end
Relational Operators
The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are as follows:
S.N | Operator | Meaning |
1 | == | Equal to |
2 | != | Not equal to |
3 | > | Greater than |
4 | < | Less than |
5 | >= | Greater than or equal |
6 | <= | Less than or equal to |
The outcome of these operations is a boolean value. He relational operators are most frequently used in the expressions that control the if statement and various loop statements. The relational operator can be illustrated using following program.
public class RelatioalOpDemo { public static void main(String[] args) { int a =4; int b = 1; boolean c = a<b; System.out.println("a = "+a); System.out.println("b = "+b); System.out.println("c = "+c); System.out.println("a>b is "+(a>b)); } }
The output of the above program is:
a = 4
b = 1
c = false
a>b is true
Boolean Logical Operators
The Boolean logical operators operate only on boolean operands. That is, the boolean logical operators are used to combine two or more relational operator to produce single boolean value.
The following table shows logical operators and their meaning
S.N | Operator | Name |
1 | & | Logical AND |
2 | | | Logical OR |
3 | ^ | Logical XOR(Exclusive OR) |
4 | || | Short circuit OR |
5 | && | Short Circuit AND |
6 | ! | Logical unary NOT |
7 | &= | AND assignment |
8 | |= | OR assignment |
9 | ^= | XOR assignment |
10 | == | Equal to |
11 | != | Not Equal to |
12 | ?: | Ternary if then –else |
The logical Boolean operators, &,|, and ^, operate on boolean values in the same way that they operate on bits of an integer. The logical! operator inverts the Boolean state. !true =false and! false = true. The following table shows the effect of each logical operation.
A | B | A|B | A&B | A^B | !A |
False | False | False | False | False | True |
True | False | True | False | True | False |
False | True | True | False | True | True |
True | True | True | True | False | False |
Let us consider the following program
public class BoolLogic { public static void main(String[] args) { boolean a = true; boolean b = false; boolean c = a|b; boolean d = a&b; boolean e = a^b; boolean f = (!a&b)|(a&!b); boolean g = !a; System.out.println("a = "+a); System.out.println("b = "+b); System.out.println("a|b = "+c); System.out.println("a&b = "+d); System.out.println("a^b = "+e); System.out.println("(!a&b)|(a&!b) = "+f); System.out.println("!a = "+g); } }
The output of the above program is
a = true
b = false
a|b = true
a&b = false
a^b = true
(!a&b)|(a&!b) = true
!a = false
Short –Circuit Logical Operators
Java provides two interesting Boolean operators not found in many other computer languages. These are secondary versions of the Boolean AND and OR operators and are known as short-circuit operators. The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is. If we use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right hand operand when the outcome of the expression can be determined by the left operand alone. This is very useful when the right hand operand depends on the left one being true or false in order to function properly.
Let us consider the following code segment
if(denom!=0&&num/denom>10)
{
….
}
When short-circuit form of AND (&&) is used, there is no risk of causing a run time exception when denom is zero.
The Assignment Operator
The assignment operator is the single equal sign,=. The assignment operator works in Java much as it does in any other computer language. It has this general form:
var = expression;
Here, the type of the var must be compatible with the type of expression.
The assignment operator does have one interesting attribute that we may not be familiar with; it allows us to create a chain of assignments. For example, consider this fragment:
int x, y, z;
x = y = z = 100;
This fragment sets the variables x, y and z to 100 using a single statement. This work because the = is an operator that yields the value of the right hand expression. Thus, the value of the right hand expression. Thus, the value z = 100, which is then assigned to y, which in turn is assigned to x. Using a “ chain of assignment” is an easy way to set a set of a group of variables to a common value.
The?: Operator
Java includes a special ternary (three way) operator that can replace certain types of if-then- else statements. The?: has following form.
expression1? expression2:expression3
Here, exppression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated, otherwise, expression3 is evaluated.
Let us consider the following program:
public class Ternary { public static void main(String[] args) { int i, k; i=10; k = i<0?-i:i; System.out.println ("Absolute value of i = "+k); i=-10; k = i<0?-i: i; System.out.println ("Absolute value of i = "+k); } }
The output of the above program is:
Absolute value of i = 10
Absolute value of i = 10
Operator Precedence: The precedence of a Java operator is given as follows:
Highest | |||
() | [] | ||
++ | — | ||
* | / | ~ | ! |
+ | – | ||
>> | >>> | << | |
> | >= | < | <= |
== | != | ||
& | |||
^ | |||
| | |||
&& | |||
|| | |||
?: | |||
= | op= | ||
Lowest |
Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is often necessary to obtain the result we desire. For example, consider the following expression:
a>>b+3
This expression first adds 3 to b and then shifts a right by that result. That is, this expression can be rewritten using redundant parenthesis like this:
a>>(b+3)
However, if we want to first shift a right by b positions and then add 3 to that result, we will need to parenthesize the expression like this:
(b>>b)+3