Showing posts with label Rogers Cadenhead. Show all posts
Showing posts with label Rogers Cadenhead. Show all posts

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.