Turn Desktop View Off
by Dinesh Thakur Category: Operators and Expressions

An operator is a special symbol that tells the compiler to perform a specific mathematical or logical operation on one or more operands where an operand can be an expression. An operation is an action(s) performed on one or more operands that evaluates mathematical expressions or change the data.

In Java, the operator can be either unary, binary or ternary. If an operator operates on single operand then it is termed as an unary operator. If an operator operates on two operands, it is called the binary operator. The operator that works with three operands is called the ternary operator.

Java provides a rich set of operators. Some of Java operators are inherited from C/C++ language while many other new operators are introduced in it.

Arithmetic Operators

All the basic arithmetic operations can be carried out in Java. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in Java language. Arithmetic operators used to perform arithmetic operations. The Arithmetic operators are binary operators that work with integers, floating point numbers and even characters (i.e., they can use with any primitive type except the boolean). There are five arithmetic operators available in Java which include addition (+), subtraction (-), multiplication (*), division (/) and modulus (%) operator. The modulus operator tells us what would be the remainder after integer division performed on a particular expression. Unlike C/C++, the modulus operator can also be applied to floating point values. The rest of the operators have the same meaning as they have in mathematics.

Types of Operator

The operands acted on by arithmetic operators must represent numeric values. Thus the operands can be integer quantities, floating point quantities or characters. The Arithmetic operators when used with characters, operate on Unicode values of the characters.

The result of the division of one integer quantity by another is referred to as integer division as this operation results in a quotient without a decimal point. On the other hand, if a division is carried out with two floating point numbers or with one floating point and one integer number, the result a floating point quotient.

Now let us suppose a and b are two operands that can have data type to that of int or double, the result obtained by carrying out various operations with arithmetic operators shown below.

arithmetic operators

NOTE: 6%0 causes ArithmeticException; 7/0.0 evaluates to positive infinity and o. 0/0.0 evaluates to NaN.

To check how adding -ve sign to an integer quantity effects the result, consider the different set of values assigned to a and b. Now on performing the following operations, the results obtained as shown below :

adding -ve sign to an integer

Thus, it is clear from the table, how the results are affected by assigning different values to a and b. The quotient obtained is negative, if both operands are of different sign and if both are of the same sign, the result is positive. In the case of modulus operator(%), the remainder has the same sign as the sign of the first operand.

The operators within Java are grouped hierarchically according to their precedence (i.e., the order of evaluation). Operators with higher precedence are carried out before operators of lower precedence. Amongst the arithmetic operators; *, / and % fall in one precedence group and + and - fall into another. The first group has a higher precedence than the second. Therefore, multiplication, division and remainder operations would be carried out before addition and subtraction.

The order of evaluation of consecutive operators within the same precedence group is called associativity. The associativity left to right in each of the precedence groups mentioned above. Therefore, consecutive operators of anyone group evaluated from left to right. To know more, refer to the hierarchy of operators.

The following table represents precedence and associativity of arithmetic operators in order of precedence.

precedence and associativity of arithmetic operators

There is no operator for performing an exponential operation in Java. Therefore z=3**2 is invalid, but it can written as z = Math. pow (3 I 2) where pow () is a library function.
The following program shows the use of various arithmetic operators.  

//program showing arthmetic operations
public class ArthmeticOper {
      public static void main(String[] args){
           float x =10.5f, y =2.3f;
           System.out.println("x + y = "+(x + y));
           System.out.println("x - y = "+(x - y));
           System.out.println("x * y = "+(x * y));
           System.out.println("x / y = "+(x / y));
           System.out.println("x % y = "+(x % y));
      }
}
Output :
x + y = 12.8
x - y = 8.2
x * y = 24.15
x / y = 4.5652
x % y = 1.3000002

Integer Arithmetic: When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be 2 integer numbers.

Then the integer operation leads to the following results :

integer arithmetic

In integer division the fractional part is truncated

Floating Point Arithmetic: When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point arithmetic. The floating point results can be truncated according to the properties requirement. The remainder operator is not applicable for floating point arithmetic operands. Let x = 14.0 and y = 4.0 then

Floating Point Arithmetic

Mixed mode arithmetic: When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real type then the result will always be real thus 15/10.0 = 1.5.

Relational Operators 

Relational operators are also known as comparison operators used to checking the relation between two operands and bring out a decision and program accordingly. In other words, the operators used to make comparisons between two operands are called relational operators. Relational operators are binary operators and hence require two operands. The result of a relational operation is a boolean value that can only be true or false according to the result of the comparison.

Relational operators are normally used with if statements, while loop, do-while loop and for loop to make branching and looping decisions.

NOTE: All the relational operators except the equality operator (==) and the inequality operator (!=) can use with numbers and characters but not with boolean values, objects or arrays. It is when the relational operator come into the picture. Java supports the following relational operators.

Relational Operator

It is required to compare the marks of 2 students, salary of 2 persons, we can ompare them using relational operators. A simple relational expression contains only one relational operator and takes the following form :

exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given below is a list of examples of relational expressions and evaluated values.

6.5 <= 25 TRUE

-65 > 0 FALSE

10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of Java language such as if, while and for statements to decide the course of action of a running program.

Also, the arithmetic operators have higher precedence over the relational operators.
The following program shows the use of relational operators.

//program showing Relational Operations
public class RelationalOper {
      public static void main(String[] args){
         float x =5, y =3;
         System.out.println("x > y = "+(x > y));
         System.out.println("x < y = "+(x < y));
         System.out.println("x <= y = "+(x <= y));
         System.out.println("x >= y = "+(x >= y));
         System.out.println("x == y = "+(x == y));
         System.out.println("x != y = "+(x != y));
     }
}
Output :
x > y --> true
x < y --> false
x <= y --> false
x >= y - -> true
x == y --> false
x != y --> true

Logical Operators

Logical operators are used to combine one or more relational expressions that results in formation of complex expressions known as logical expressions. Like relational operators, the logical operators evaluate the result oflogical expression in terms of boolean values that can only be true or false according to the result of the logical expression. Java has the following logical operators, they compare or evaluate logical and relational expressions.                             

Logical Operators

In Java, there are six logical operators: logical AND (&), logical OR (|), logical exclusive OR i.e. XOR (^), logical negation (!), conditional AND (&&), conditional OR (||). All the logical operators are binary operators except logical negation which is a unary operator.

Conditional AND (&&): This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true.

Example :

a > b && x = = 10

The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.

Conditional OR (||): The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true.

Example :

a < m || a < n

The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.

logical negation (!): The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression.

For example :

! (x >= y)

The NOT expression evaluates to true only if the value of x is neither greater than or equal to y.

The logical AND (&) operator evaluates to true if and only if both its operands evaluates to true. The logical OR (|) operator evaluates to true if and only if either of its operands evaluate true. The logical exclusive OR i.e. XOR (^) operator evaluates to true if and only if either, but not both, of its operands are true. In other words, it evaluates to false if both the operands are false. The logical NOT(!) operator takes a single operand and evaluates to true if the operand is false and evaluates to false if the operand is true.
NOTE: With boolean operands, the exclusive OR operator is equivalent to != operator.

For example, if num = 15, ch = 'y', percentage = 70.5, where num is int type variable, ch is char type variable and percentage is double type variable, then

(nun%5==0)&(nun%3==0) --> true
(nun%6==0) | (nun%4==0) --> false
!(percentage < 60) --> true
(ch=='Y') || (ch=='y') --> true

The conditional AND (&&) and conditional OR (||) perform the same logical function as that of logical AND (&) and logical OR (|) operators respectively, but they avoid evaluating their right operand if the truth of the expression is determined by the left operand.
In logical conditional AND(&&), if the left operand evaluates to false then the right operand will not be evaluated because the expression is already guaranteed to be false. For example:

Consider an expression.

(5>6) && (7>3)
As the conditional expression (5>6) evaluates to false so the condition expression (7>3) to the right of the conditional AND operator will not be evaluated because the expression is guaranteed to be false.
In the logical conditional OR( II ), if the left operand evaluates to true then the right operand will not be evaluated because the expression is already guaranteed to be true. For example, consider an expression
(8>3) || (3>7)
As the conditional expression 8>3 evaluates to true so the conditional expression (3>7) to the right ofthe conditional OR operator will not be evaluated because the expression is guaranteed to be true.
The logical operators have the following precedence

Logical Operators precedence

All the logical operators except logical NOT operator have lower precedence than the relational and arithmetic operators.
The following program shows the use of logical operators

//program showing Logical Operations
publicclass LogicalOper {
      publicstaticvoid main(String[] args){
          int x =6, y =4, z =5;
          System.out.println("x > y & y > z"+(x > y & y > z));
          System.out.println("x > y | y > z"+(x > y | y > z));
          System.out.println("x > y ^ y > z"+(x > y ^ y > z));
          System.out.println("x > y && y > z"+(x > y && y > z));
          System.out.println("x > y || y > z"+(x > y || y > z));
          System.out.println("!(x > y)"+(!(x > y)));
      }
}
Output :
x>y & y>z --> false
x>y | y>z--> true
x>y ^ y>z --> true
x>y && y>z --> false
x>y || y>z --> true
!(x>y) --> false

Assignment Operators 

The assignment operator (=) is the most commonly used binary operator in Java. It evaluates the operand on the right-hand side and then assigns the resulting value to a variable on the left-hand side. The right operand can be a variable, constant, function call or expression. The type of right operand must be type compatible with the left operand. The general form of representing an assignment operator is
variable = expression/constant/function call
a = 3;//constant
x = y + 10;//expression
In the first case, a literal value 3 is stored in the memory location allocated to variable a. In the second case, the value of expression y+ 10 is evaluated and then stored in memory allocated to variable x.
Consider a statement x = y = z = 3;
Such type of assignment statement in which a single value given to some variables is called multiple assignment statements, i.e. value 3 is assigned to the variables x, y and z. The assignment operator (=) has a right to left associativity, so the above expression is interpreted as
(x = (y = (z = 3)));
Here, first, the value 3 is assigned to z, then the value stored in z is assigned to y and then finally y is assigned to x. Now let us consider a statement
x = 3 = 5;

This type of statement is an invalid assignment statement, and it generates an error.
There is another kind of assignment statement which combines a simple assignment operator with five arithmetic binary operators and six bitwise operators. This type of operator is known as the compound assignment operator. The general syntax of the compound assignment operator is
variable operator= expression/constant/function call
For example: Suppose i is a variable of type int then the statement,
i += 5;
will add the literal 5 to the variable i and store the result back into the variable i.

The commonly used shorthand assignment operators are as follows                                                           ShortHand Assignment Operator

Such operators make the statement concise, so they are also called shorthand assignment operator. The expression a = a+b is almost same as that of a += b but the main advantage of the shorthand assignment operator is that the operand is that the operand on the lefthand side of the assignment evaluated only once. The assignment operators have the lowest precedence as compared to other operators. Only one variable is allowed on the left-hand side of the expression. Therefore a = x * y is valid, and m * n = 1 is invalid

It is to keep in mind that an assignment operator (=) and equality operator (==) are different. The assignment operator is used to assign a value to a variable whereas the equality operator used to compare two operands. These operators cannot use them in place of each other. The assignment operator(=) has lower precedence than arithmetic, relational, bitwise, and logical operators.

Bitwise Operators

Java provides an extensive bit manipulation operators for programmers who want to communicate directly with the hardware. These operators are used for testing, setting or shifting individual bits in a value. To work with these operators, one should be aware of the binary numbers and two's complement format used to represent negative integers.

The bitwise operators can be used on values of type long, int, short, char or byte , but cannot use with boolean, float, double, array or object type.

The bitwise operators are.

bitwise operators in Java

The bitwise AND(&) bitwise OR(|) and bitwise Exclusive OR (^) are the three logical bitwise operators. These are the binary operators which compare the two operands bit by bit. If either of the operands with a bitwise operator is of type long, then the result long. Otherwise, the result is of type int.

logical bitwise operators

Here, a and b are corresponding bits of two operands.

Bitwise AND (&) operator combines its two integer operands by performing a logical AND operation on their bits. It sets each bit in the result to 1 if corresponding bits in both operands are 1. One of the applications of bitwise AND operator is forcing selected bits of an operand to O.
Bitwise OR (|) operator combines its two integer operands by performing a logical OR operation on their bits. It sets each bit in the result to 1if the corresponding bits in either or both of the operands are 1. One of the applications of bitwise OR is forcing selected bits of an operand to 1.

Bitwise Exclusive OR operator (^) combines its two integer operands by performing logical XOR operands on their bits. It sets each bit in the result to 1 if the corresponding bits in two operands are different. One of the applications of bitwise Exclusive OR operator is to change O's to 1's and 1's to 0's.

To illustrate the use of these three operators, let us assume that a, b, c are defined as integer variables as follows :
int a=18,b=25,C;
As they are of type int, so they require 32 bits for their storage, so binary representation for a and b is,

Binary representation of a is 0000 0000 0000 0000 0000 0000 0001 0010
Binary representation of b is 0000 0000 0000 0000 0000 0000 0001 1001
In our discussion, we shall be only considering right 16 bits and ignoring 16 bits of the 32-bit format because doing this not affect the result.
The statement c = a&b; will result in

a      0000 0000 0001 0010
b      0000 0000 0001 1001
a&b  0000 0000 0001 0000

Similarly, the statement c = a|b; result in

a     0000 0000 0001 0010
b     0000 0000 0001 1001
a|b  0000 0000 0001 1011

Similarly, the statement c = a^b; result in

a     0000 0000 0001 0010
b     0000 0000 0001 1001
a^b  0000 0000 0000 1011
Bitwise One's Complement operator (~) Bitwise complement operator(~) is a unary operator. It inverts each bit of its operand, i.e., Is become 0s and 0s become Is. This operator can use to

• To encrypt the contents of a file which can later decrypted.
• To store negative numbers in some computers that supports one's complement method for storing negative number.
  Let us consider an operand a = 0000 0000 0001 0010 then on performing (~a) we get
  ~a = 1111 1111 1110 1101
Bitwise shift left operator (<<) shifts the bits of the left operand to the left by some positions specified by the right operand. The high order bits of the left operand lost, and 0 bits are shifted in from the right. It has the following syntax
operand1 << operand2
Here, operand1 is the binary representation of a number to be the shifted and operand2 represents the number of positions by which it shifted. Let us consider an operand a = 0000 0101 0000 0011. On performing a<<3 we get,

bitwise shift left operator

Here, 3 zero's are inserted on the right as an operand is shifted to left thrice. The effect of shifting an operand to the left by one-bit position is equivalent to multiplying the value by 2. So if the initial value of the operand is 14, then shifting left by 1-bit position results in 14 x 2= 28.

NOTE: If the left operand is of type long then the right operand should be between 0and 63. Otherwise, the right operand should be between 0 and 31 because the left operand is assumed to be of type int.

Bitwise Shift Right operator (>>) shifts the bits of the left operand to the right by some positions specified by the right operand. The low order bits of the left operand lost, and the high order bits shifted in are either 0 or 1 depending upon whether the left operand is positive or negative. If the left operand is positive, Os shifted into the high order bits, and if the left operand is negative, 1's shifted instead. It has the following syntax.

operand1>>operand2

Here, operand1 is the binary representation of a number to be shifted, and operand2 represents the number of positions by which it shifted.
Let us consider an operand a = 0000 0101 0000 0011 then on performing a>>3 ,we get

bitwise shift Right operator

Here, 3 zero's are inserted on the left as the operand shifted thrice. The effect of shifting an operand to the right by one-bit position is equivalent to dividing the value by 2. So in the above example, a is divided by 23 (i.e., 8).

Similarly, consider another example where the given number is negative which is indicated by having the last left bit (i.e., sign bit) to be 1. So if a = 1000 0101 0000 0011 then on performing a>>3 we get,

bitwise Shift Right operator is case of negative numbers

Bitwise Shift Right with zero fill (>>>) operator is similar to bitwise shift right (>>) operator with the exception that it always shifts zero's into the high order bits of the result regardless of the sign of the lefthand operand. Let us consider an example where we have a number a = 1000 0101 0000 0011 then on performing a>>>3 we get,

bitwise Shift Right with zero fill operator

The order of evaluation of bitwise operators is as follows: The bitwise one's complement operator is evaluated first, followed by left shift operator, the shift right operator and the shift right with zero fill operator then followed by logical bitwise operators.
Let us now consider a program that shows the use of bitwise operators.

//program showing Bitwise Operators
import static java.lang.Long.*;
publicclass BitwiseOper {
    publicstaticvoid main (String[] args){
       short x =20, y =0xaf;
       short z =-24;
       System.out.println("x & y --> "+(x & y));
       System.out.println("x | y --> "+(x | y));
       System.out.println("x ^ y --> "+(x ^ y));
       System.out.println("z << 2 --> "+(z <<2));
       System.out.println("z >>> 2 --> "+(z >>>2));
       System.out.println("z >> 2 --> "+(z >>2));
    }
}
Output :
x & y --> 4
x | y --> 191
x ^ y --> 187
z << 2 --> -96
z >>> 2 --> 1073741818
z >> 2 --> -6
Note: The binary representation of x is 10100 (binary equivalent of 20), y is 10101111. The negative numbers are stored in 2's complement form.

Conditional Operator (?:)

Conditional operator (?:) is the only ternary operator available in Java which operates on three operands. The conditional operator together with operands form a conditional expression which takes the following form
expr1? expr2:expr3
Where expr1 is a boolean expression and expr2, and expr3 are the expressions of any type other than void. The expr2 and expr3 must be of the same type.
The value of the expression involving the conditional operator is determined as follows,
expr1 is a test condition which evaluates first. If it is true, then expr2 is evaluated, and this becomes the value of a conditional expression. However, if it is false, then expr3 is evaluated, and this becomes the value of a conditional expression. The value of the conditional expression can also assign to another variable.

Eg. c = (a > b) ? a : b;
j = (i > 10) ? 1 : 100;

k = (a > b)?
System.out.println(a);
System.out.println(b);
d = (a > b)? ((a>c)?a:c):((b>c)?b:c);
In the first example, if (a>b) is true then a becomes value of the conditional expression and if it is false then b becomes value of the conditional expression which is finally assigned to c.

conditional expression

Similarly, the second and third statements evaluate.
The conditional operator is a shorthand version of the if-else statement. The first example can also represent as,
if (a > b)
c = a;
else
c = b;
The conditional operator has higher precedence than the assignment operator.
Let us consider a program that shows the use of the conditional operator,

//program to find greatest of three numbers using conditional operator
import java.util.Scanner;//program uses Scanner class
publicclass Greatest {
    publicstaticvoid main(String[] args){
       int a,b,c,result;//Create scanner object to obtain input from keyboard
       Scanner input =newScanner(System.in);
       System.out.print("Enter the three number -->");//prompt for input
       a = input.nextInt();//Read first number
       b = input.nextInt();//Read Second number
       c = input.nextInt();//Read Third number
       result =(a>b)?((a>c)?a:c):((b>c)?b:c);
       System.out.println(Result+"is Greatest");
   }
}
Output:
Enter the three numbers ---> 33 55 11
55 is Greatest

Unary Operators

The operators that act upon a single operand to produce a new value are known as Unary operators.

Unary Operator

The Unary operators have higher precedence than the operators we have already discussed.

Unary Minus(-)

In this operator, a minus sign precede an operand to negate its value. Here, operand can be any integer or floating point value.
If a = 10 then -a =-10
and a = -10 then -a = -(-10) = 10
Thus unary minus (-) operator reverses the sign of an operand. The positive operand is changed to negative and vice versa.
Some examples are,
-85; -0.3; -(a+b); -4(x+y);
The Unary Minus is distinctly different from arithmetic subtraction operator even though both have the same minus symbol.
a = 10--x can be interpreted as a = 10 -(-x)
where fIrst negative sign stands for arithmetic subtraction operator (Binary Qperator) and second negative sign is used for unary minus.

Increament Operator (++) and Decrement Operator(--)

In certain situations, there is need to increase or decrease an operand by 1,continuously for some time. So, Java provides an increment operator(++) and a decrement operator (--) to increase and decrease the operand by 1 respectively. Here, an operand maybe a variable, an element of an array etc. If i is a variable then ++i is equivalent to i = i+1 which means that value of a variable is increased by 1. Similarly, --i is equivalent to i = i-1 which on execution decreases the value of variable by 1.
There are two ways of representing increment and decrement operators.
a) as a prefix i.e. operator precedes the operand. Eg. ++i; --j ;
b) as a postfix i.e. operator follows the operand. Eg. i--; j++;
In case of prefIx increment operator (Eg. ++i), first the value of the operand will be incremented then incremented value will be used in the expression in which it appears.
In case of postfix increment operator (Eg. i++), first the current value of the operand is used in the expression in which it appears and then its value is incremented by 1.
In order to understand the difference between prefix and postfix increment operator, let us consider an example. Suppose an integer variable i holds a value 10, then on executing statement.
j = i++;

results in j = 10 and i = 11. Since, it is a postfix increment operator so value of i(10) is first assigned to j and then it is incremented by 1 (i.e 10 + 1 = 11). So the above statement is equivalent to following two statements executed one after the other.

Statement 1

If instead of the above statement, we have a statement j = ++i; then it results in j = 11 and i = 11. Since, it is a prefix increment operator so value of i is first incremented by 1 (i.e 10 + 1 = 11) and then it is assigned to j(11), so the statement j = ++i is equivalent to

Statement 2

In the similar way, the postfix and the prefix decrement operator works. The only difference is that the value of the variable is decremented by 1.

Cast Operator (Type)

In certain situations, there is a need to convert a variable from one data type to another within the expression. The data conversion is performed explicitly by the programmer who is accomplished using a cast operator. The Unary operators have higher precedence than the arithmetic operators. Also, the unary operators have associativity from right to left. Thus, they would be evaluated right to the left in a given expression.

Other Java Operator

Java also provides some other operators. We shall now discuss these operators briefly.

String Concatenation Operator(+)

In addition to adding numbers, the + operator can also be used to concatenate two strings.
The + operator is interpreted as a string concatenation operator whenever at least one of its operands is a string. If either of the operands is a string, then the other operand is implicitly converted to a string.
For example : Consider the statement,
System.out.print1n("Sum = " +2+5); //prints Sum = 25
String s = "A" + "B"; //stores A+B in s.
System.out.print1n("Resu1t = " + 10/3.0f); //Prints Result = 3.3333333
NOTE: When you want to combine addition with concatenation, it is necessary to use parentheses.

instanceof Operator

The instanceof operator is an object reference operator which is used to check the type of an object reference. The instanceof operator requires an object or array value as its left operand and name of a reference type as its right operand. This operator evaluates to true if the object or array on its left-hand side is an instance of the specified type; otherwise, it returns false.

person instanceof Manager

evaluates true if the object person belongs to the class Manager otherwise, it evaluates to false.

Dot Operator

The dot operator (.) is used to access the fields and methods of an object. For example: If s is an object of class Student then to access the field rollNumber of the object s, we use the dot operator as follows,
s.rollNumber
Similarly, if you want to access getData () method of s object then we use the dot operator as follows,
s.getData();

new Operator

In Java, the new operator is used to create an object of a class or an array. It is a unary prefix operator. To create an object, use the new operator with the name of the class whose object you want to create, followed by parentheses. The parentheses can be empty or can contain arguments, For example, The statement
Student s = new Student();
creates an object s of class Student.

Precedence and Associativity of Operators

When an expression contains more than one operator such as 5+8*3, its interpretation may not be immediately evident, i.e., does 5+8*3 means "Add 5 and 8, then multiply the result by 3" or does it mean "Multiply 8 and 3 and then add the result to 5". So like other languages, Java uses operator precedence rule to resolve this potential ambiguity. Precedence determines the order in which operations performed during the evaluation of an expression. Operators with higher precedence are evaluated before operators of lower precedence regardless of the order in which they appear. Precedence of operators helps in reducing confusion during the evaluation of an expression. Eg. Consider the same expression 5+8*3

Here, the multiplication operator has higher precedence than the addition operator. So multiplication operation is performed first that computes the value of 8*3=24 which then added to 5, and thus the result is 29.

Operator precedence alone is not enough when an expression contains two or more operators with the same precedence. For example, The expression 4*3/2 contains arithmetic * and / operators who have the same precedence. In such a situation, the associativity of the operator comes into play. Associativity governs the order in which multiple operators with the same precedence are evaluated either from left to right or right to left. Most operators are left to right associated; this means that compiler begins evaluation from the left of expression and then move towards the right. The unary and assignment operators have right to left associativity, the compiler begins
evaluation from the right of the expression and more towards left. Eg. In the expression 4*3/2, the operator * and / have the same precedence, and their associativity is from left to right. It means, the compiler first compute 4*3 to 12 which is then divided by 2 give the result 6. Consider another example, x = y = z. Here the expression is evaluated right to the left i.e., first z is assigned to y, and then y is assigned to x.

Operator Precedence and Associativity in JavaThe first group has the highest precedence, and the last group has the lowest precedence. The operators who belong to the same group have equal precedence. Each group has associativity either from left to right or from right to left.
A programmer can change the default operator precedence through the use of parentheses that explicitly specify the order of operations. In such a case, an innermost operation is carried out first then the next innermost operation and so on.

The following points should consider while evaluating the operators according to the hierarchy of operators.

1. If there is more than one set of parentheses, then the operations within the innermost parentheses performed first, followed by the operations within the second innermost and so on. Consider the example,
m = ((a+b) *c) *d) ;
In this statement, a+b performed first because it is in the innermost parentheses, then the result of it would be multiplied by c, and then their result would be multiplied with d.
2. Always remember to use a pair of parentheses. A careless imbalance of the right and left parentheses is a common error. Consider the example,
x = (((a+b)*(c+d)/f;

In this statement, there is an imbalance of parentheses, a bracket ()) after c+d is missing, so it generates an error.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.