Rich
Rich

Reputation: 36806

float/int implicit conversion

I'm doing multiplication and division of floats and ints and I forget the implicit conversion rules (and the words in the question seem too vague to google more quickly than asking here).

If I have two ints, but I want to do floating-point division, do I need only to cast one or both of the operands? How about for multiplication — if I multiply a float and an int, is the answer a float?

Upvotes: 23

Views: 54189

Answers (6)

supercat
supercat

Reputation: 81115

Java ranks primitive types in the order int < long < float < double. If an operator is used with different primitive types, the type which appears before the other in the above list will be implicitly converted to the other, without any compiler diagnostic, even in cases where this would cause a loss of precision. For example, 16777217-1.0f will yield 16777215.0f (one less than the correct value). In many cases, operations between a float and an int outside the range +/-16777216 should be performed by casting the int to double, performing the operation, and then--if necessary--casting the result to float. I find the requirement for the double casting annoying, but the typecasting rules in Java require that one either use the annoying double cast or suffer the loss of precision.

Upvotes: 0

You can’t assign to an int result from division of a float by an int or vice-versa.

So the answers are:

If I have two ints, but I want to do floating point division…?

One cast is enough.

If I multiply a float and an int, is the answer a float?

Yes it is.


float f = 1000f;
int i = 3; 

f = i; // Ok
i = f; // Error

f = i/f; //Ok 0.003
f = f/i; //Ok 333.3333(3)

i = i/f; //Error
i = f/i; //Error

Upvotes: 36

user207421
user207421

Reputation: 310850

The simple answer is that Java will perform widening conversions automatically but not narrowing conversions. So for example int->float is automatic but float->int requires a cast.

Upvotes: 6

blizpasta
blizpasta

Reputation: 2604

If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

(Source: Java language specifications - 4.2.4)

if I multiply a float and an int, is the answer a float?

System.out.println(((Object)(1f*1)).getClass());//class java.lang.Float

(If you use DrJava, you can simply type ((Object)(1f*1)).getClass() into the interactions panel. There's a plugin for DrJava for Eclipse too.)

Upvotes: 7

Matt Ball
Matt Ball

Reputation: 359776

In order to perform any sort of floating-point arithmetic with integers, you need to convert (read: cast) at least one of the operands to a float type.

Upvotes: 7

Bozho
Bozho

Reputation: 597016

To demonstrate:

 int i1 = 5;
 float f = 0.5f;
 int i2 = 2;
 System.out.println(i1 * f);
 System.out.println(i1 / i2);
 System.out.println(((float) i1) / i2);

Result:

2.5
2 
2.5

Upvotes: 11

Related Questions