Steve Chambers
Steve Chambers

Reputation: 39404

Does the Java compiler optimize type conversions when mixing numeric types?

Could there be any difference in speed (however small) between Case 1 and Case 2 below?

double total = 12.34
double percentage = 56.78;
double amount;

// Case 1:
amount = (100 - percentage) * total;

// Case 2
amount = (100.0 - percentage) * total;

Or does Java automatically convert the integer literal (100) to a double (100.0) at compile time?

Upvotes: 0

Views: 47

Answers (1)

qwerty
qwerty

Reputation: 2095

Decompiled version shows that output will be same for both cases.

But as a best practice Case 2 will be more readable and understandable.

double d1 = 12.34D;
double d2 = 56.78D;

double d3 = (100.0D - d2) * d1;

d3 = (100.0D - d2) * d1;

Upvotes: 1

Related Questions