0

Java arithmetics operations could be tricky

Posted by Guillermo GarcĂ­a on 10:48 PM in , ,
When you use arithmetic operators, usually you don't care about the result format, maybe because is too obvious or maybe by omission. Look at this example:

int a = 4;
int b = 2;

int result = a/b;
System.out.println("Result: "+result);

You will get "Result: 2" right? And this is correct, but what happens if we change it?

int a = 5;

What will you get on your screen now? The correct answer is 2.5, but you will get only 2. So, dividing two integers, do you get one integer? Yes, and it is very consistent with the "promotion rules" of primitive numbers in Java.

When you add, rest, multiply or divide two numbers, the result will be in the format of the "bigger" operand. For example:
  • int + long will return a long.
  • short * int will return an int
  • int / int will return an int ... What happens with the decimal values? Simple, they are dismissed
If you want to preserve the decimal value, you have to "force" the expression to return a float or a double value. How can you do that? "Casting" at least one of the operators to a double, for example, and settling your return variable as a double. Look at this:

int a = 5;
int b = 2;

double result = a/(double)b;
System.out.println("Result: "+result);

And the result now is the correct one: 2.5 . It is a very important point of Java operators, of which you must be aware if you don't want any hassling bug in your calculus.

0 Comments

Copyright © 2009 ggarciao.com
- Cup of Java -
All rights reserved.