3

Take these two snippet for example:

Case 1:

Scanner s = new Scanner(System.in);
int n = s.nextInt(); /** take user input **/

n *= Double.NEGATIVE_INFINITY;

and

Case 2:

int k=10;
double kk = 10.10;

int rst = k*kk;

In both the cases, I am not doing any typecasting from my side, but Case 1 executes and prints value of n correctly but Case 2 throws an error, can not convert from double to int. Why this difference?

Rahul
  • 44,383
  • 11
  • 84
  • 103
NoobEditor
  • 15,563
  • 19
  • 81
  • 112

3 Answers3

5

The first works and the second doesn't because the *= += -= etc add an automatic cast.

If, for example, you were to change your second example to;

int k=10;
double kk = 10.10;
k*= kk;

It should work. Alternatively you could just add an explicit cast like so rst = (int)(k*kk);

Rudi Kershaw
  • 12,332
  • 7
  • 52
  • 77
1

The arithmetic promotion in Java happens when you apply an arithmetic operation on two variables with different data-types. In this case the compiler will convert the data type of one operand in the binary arithmetic operation to the type of the other operand.

In your case, for multiplying an int and a double, the int is promoted to double, and the result is double. So, it can't be stored into an int.

See more at: http://www.codemiles.com/java/arithmetic-promotion-t3487.html#sthash.sdHtt7pG.dpuf

Andres
  • 10,561
  • 4
  • 45
  • 63
0

The result of the multiplication of an integer (int) and a floating point in java will always result in a floating point (double). You are assigning this result to the integer rst which requires casting.

jeroen_de_schutter
  • 1,843
  • 1
  • 18
  • 21