Showing posts with label multiplication. Show all posts
Showing posts with label multiplication. Show all posts

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.

Friday, 26 April 2013

Multiplication in Java

For many situations, the int data type will be adequate for storing integer variables. It can hold values between (roughly) + or - 2 billion. You can multiply two integers as follows:

UBUNTU > cat prog7.java
public class prog7
{
public static void main (String args[])
  {
  // Declare 2 integers:
  int num1 = 1234;
  int num2 = 4321;

  // Multiply them together:
  int num3 = num1 * num2;

  // Display the result:
  System.out.println("num1 = " + num1);
  System.out.println("num2 = " + num2);
  System.out.println("num1 * num2 = " + num3);
  }
}
UBUNTU > javac prog7.java
UBUNTU > java prog7
num1 = 1234
num2 = 4321
num1 * num2 = 5332114
UBUNTU >


... but what happens if the result is too big to store in an int variable?

UBUNTU > cat prog8.java
public class prog8
{
public static void main (String args[])
  {
  // Declare 2 integers:
  int num1 = 123456;
  int num2 = 654321;

  // Multiply them together:
  int num3 = num1 * num2;

  // Display the result:
  System.out.println("num1 = " + num1);
  System.out.println("num2 = " + num2);
  System.out.println("num1 * num2 = " + num3);
  }
}
UBUNTU > javac prog8.java
UBUNTU > java prog8
num1 = 123456
num2 = 654321
num1 * num2 = -824525248
UBUNTU >

According to my calculator, the result should be 80,779,853,376 so some arithmetic overflow must have taken place. As soon as I find out how to handle this, I will do a worked example to demonstrate.

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.