Lesson 4: Java Precedent Rules

Java programming made easy


Java is a language and just like any other spoken language, it too does have rules on how specific expressions are evaluated. When we talk of Java precedent rules, we are referring to the way decision statements are evaluated. Think of math precedent rules known by the mnemonic PEMDAS or BODMAS.

As a programmer, you can choose to override some of these precedent rules by using parenthesis just as you will in Maths to indicate what you really want to be done first. Here are the rules as defined by java in order of highest precedent
  1. Unary operators: +, -, ++, --, !
  2. Binary arithmetic operators: *, /, %
  3. Binary arithmetic operators: +, -
Unary operators are those operators that are are done on a single variable just as incrementing or decrementing it. They look like this:
index++, ++index, +index, -index, !ok, !print, +go-
Binary arithmetic operation are similar to the math one and they too take multiplication and division as more important than addition and subtraction just as in math. Here are a few binary arithmetic expressions:
// Variables
int thisOne = 1;
int thatOne = 1;
int joe = thisOne;
int jade = thatOne;
int playTime = 0;
// Binary arithmetic operations
++thisOne; // increment to 2
joe += thatOne;// has the sam value as thatOne
playTime = jade + joe;// 1 + 2
thatOne = jade * playTime;//1 * 3
     
if (playTime != 0)
{
       if (playTime > joe)
              System.out.println("playTime > joe");
       else
              System.out.println("joe > playTime");
}
     
// Print all variables one line at a time
System.out.println("thisOne = " + thisOne + "\n" + "thatOne = " + thatOne + "\n" + "joe = " + joe + "\n" + "jade = " + jade + "\n" + "playTime = " + playTime + "\n");
The code snippet gives the following output 
playTime > joe
thisOne = 2
thatOne = 3
joe = 2
jade = 1
playTime = 3

There are situations where an expression involves operators of equal precedent. This won't confuse Java because there are also rules which governs how they will be evaluated. These two exception are:
  1. Unary operators of equal precedent are grouped from right to left
  2. Binary operators are grouped from left to right
The following code snippet aims to show the exception rules when precedents are equal.

+-+thisOne
Above is an expression made up of unary operators and this according to Java rules have equal precedence. Therefore, Java would evaluate this expression from right to left by grouping it as +(-(+thisOne)).

playTime = jade + joe - thatOne
The above expression is a binary expression and the operators all have equal precedence. According to the Java rules, it would be evaluated from left to right by grouping it as (jade + joe) - thatOne.

Share your thoughts