×

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a set of rules in Java. The idea of operator precedence is used to select the set of terms in an expression. The expressions are evaluated by the operator precedence. Parentheses() and Array subscript[] are given priority over all other operations in Java. For instance, the operators for addition and subtraction come before the left and right shift operators. 

The table below is defined with the lowest precedence operator at the top.

PrecedenceOperatorTypeAssociativity
1)=
+ =
- =
* =
/ =
% =
Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Modulus assignment
Right to left
2)? :Ternary conditionalRight to left
3)||Logical ORLeft to right
4)&&Logical ANDLeft to right
5)|Bitwise inclusive ORLeft to right
6)^Bitwise exclusive ORLeft to right
7)&Bitwise ANDLeft to right
8)! =
= =
Relational is not equal to
Relational is equal to
Left to right
9)<
< =
>
> =
instanceof
Relational less than
Relational less than or equal
Relational greater than
Relational greater than or equal
Type comparison (objects only)
Left to right
10)>>
<<
>>>
Bitwise right shift with sign extension
Bitwise left shift
Bitwise right shift with zero extension
Left to right
11)-
+
Subtraction
Addition
Left to right
12)*
/
%
Multiplication
Division
Modulus
Left to right
13)-
+
~
!
( type)
Unary minus
Unary plus
Unary bitwise complement
Unary logical negation
Unary typecast
Right to left
14)++
--
Unary  post-increment
Unary post-decrement
Right to left
15)·
()
[]
Dot-operator
Parentheses
Array subscript
Left to Right

Precedence order

The operator with the highest precedence takes priority when two operators share a single operand. In contrast to x * y + z, which is considered as (x * y) + z since the * operator has higher precedence than the + operator, x + y * z is treated as x + (y * z).

Associativity

The term "associative" refers to the operators used when two operators with the same precedence are present in an expression. To get out of that dilemma, the associativity notion is really beneficial. Consider the expression a + b - c. Since the + and - operators have equal priority, this expression will be interpreted as (a + (b - c)), since the + and - operators are right-to-left associative. The unary post-increment and decrement operators, on the other hand, are right to left associative, thus a++--b+c++ will be interpreted as ((a++)+(--b)+(c++))).

To clarify how an expression is assessed using precedence order and associativity, a definition is provided below. 

Expression: x = 4 / 2 + 8 * 4 - ( 5+ 2 ) % 3

Solution:

  1. The highest precedence operator in the preceding expression is (). Therefore, the parenthesis starts the calculation process first.

    x = 4 / 2 + 8 * 4 - 7 % 3
  2. Now that the /, *, and % operators have the same precedence and are higher than the + and -, we can solve them using the associativity idea. These operators have a left to right associative. Therefore, the / operator executes first, followed by * and% concurrently.

    x = 2 + 8 * 4 - 7 % 3
    x = 2 + 32 - 7 % 3
    x = 2 + 32 - 1
  3. Now, + and - operators both also have the same precedence, and the associativity of these operators lest to the right. So, + operator will go first, and then - will go.

    x = 34 - 1
    x = 33

Program

Filename: HighestPrecedence.java

//import classes  
import java.util.*;  
  
//creating HighestPrecedence class to evaluate the expression  
public class HighestPrecedence {  
      
    //main() method starts  
    public static void main(String[] args) {  
          
        //initialize variables with default values  
        int x = 2;  
        int y = 5;  
        int z = 12;  
          
        //calculating exp1, exp2, and exp3   
        int exp1 = x +(z/x+(z%y)*(z-x)^2);  
        int exp2 = z/x+y*x-(y+x)%z;  
        int exp3 = 4/2+8*4-(5+2)%3;  
          
        //printing the result  
        System.out.println(exp1);  
        System.out.println(exp2);  
        System.out.println(exp3);  
    }  
}  

Output

Highest precedence in Java

Related Topics

Java Imageio

The javax.imageio package contains the final class known as Java ImageIO. For easy image reading, writing, and simple encoding and decoding, the class offers a convenient way. The class offers...

4 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

TreeSet in Java

Java TreeSet with Example Java TreeSet implements the Navigable Set interface. It stores the objects in ascending order. It contains unique elements. Access and retrieval time is fast. It does not...

8 minutes read.