0

Why does ci1 contain the wrong value

Whats going on when you multiply three int and convert to long?

public class integers{

  public static void main(String []args){

    int im1 = 12*5280;
    long ci1;

    long im2 = 12*5280;
    long ci2;

    ci1 = im1 * im1 * im1;
    ci2= im2 * im2* im2;
    System.out.println(im1+" "+ci1);
    System.out.println(im2 +" "+ci2);
  }
}

Output is

63360 1507852288

63360 254358061056000

the second line is the correct answer and 63360 fts easily into an int

azro
  • 53,056
  • 7
  • 34
  • 70
MCorkers
  • 13
  • 1

3 Answers3

4

The max value an integer can hold is roughly 2 billion (2,147,483,648). The result of your multiplication is roughly 200 trillion (254,358,061,056,000). This is a case of integer overflow.

int * int * int will give you an integer before it's widened to a long and assigned to the long variable.

Michael
  • 41,989
  • 11
  • 82
  • 128
3

The multiplication is performed using the types of the operands – the type you are assigning the result to has nothing to do with it. So when you multiply those ints, there will be an overflow since 254358061056000 does not fit inside an int. Only then is the result cast to a long.

O.O.Balance
  • 2,930
  • 5
  • 23
  • 35
1

In fact, before assignment : ci1 = which is a long, java handle the right part, where it's manipulate int. int * int return an int

As the value you try to get is a long you need explicit it

You could tell java that you want to manipulate long

    public static void main(String[] args) {

    int im1 = 12 * 5280;
    long ci1;

    long im2 = 12 * 5280;
    long ci2;

    ci1 = (long)im1 * (long)im1 * (long)im1;
    ci2 = im2 * im2 * im2;
    System.out.println(im1 + " " + ci1);
    System.out.println(im2 + " " + ci2);
}
Vyncent
  • 1,185
  • 7
  • 17