Monday 13 May 2013

Operator Precedence in Java

Operator precedence is important in any programming language. This determines which of the arithmetical operators i.e. addition, subtraction, multiplication, division etc is done first.

In ICL's System Control Language (SCL), if I remember correctly, arithmetical operators all had the same precedence and were evaluated from left to right so 1 + 2 * 3 would come to 9. This is quite unusual.

In Java, multiplication and division have a higher priority than addition and subtraction but you can use brackets to override this behaviour. This is similar to a wide variety of other programming languages. You can see what I mean in the example below:

UBUNTU > cat prog27.java
public class prog27
{
public static void main (String args[])
  {
  System.out.println
  ("1 + 2 * 3 = " + (1 + 2 * 3));
  System.out.println
  ("(1 + 2) * 3 = " + ((1 + 2) * 3));
  }
}
UBUNTU > javac prog27.java
UBUNTU > java prog27
1 + 2 * 3 = 7
(1 + 2) * 3 = 9
UBUNTU > 

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.