Monday, January 30, 2017

Dividing two integers in Java

I write this entry because I wrote this question for a job interview questionnaire 5 years ago and every time I ask it only a very small percentage (about 2% so far) of programmers answer it.

So here is the scenario:
Let's say you have been given a task of dividing two integers and returning the result as float in Java
so you get this:

public static void main(String[] args)
   float x=1;
   int y=2;

   float fRet;
   
   fRet = x/y;

   System.out.println("Result: "+fRet);
}

What would be printed at the output ?
The choices are :
0
0.5
1


Well?

0 would be printed.
Now lets see why:
at this line :   fRet = x/y;
we take an integer and another integer and divide them and the result is stored in the float.
so why isn't it 0.5 I hear you ask ? 
It's because the type of the division result is of integer type.
java does not overthink primitive types (such as float,int,byte and etc') it will not automatically upcast
types so if you have 2 operands of the same type the result will be of that exact type.
so what do you get when you dividing integer by integer? you get rounding down and get 0 and that 0
is then stored in the float.
"Great !" I hear you say, "I know how to fix it! Just change one of the operands to type float like so:"

public static void main(String[] args){
   float x=1;
   int y=2;

   float fRet;
   
   fRet = x/y;

   System.out.println("Result: "+fRet);
}

And you will be correct, the output of that will be 0.5.
But let's say you get the parameters in function of type int like so:

public static float divide(int x,int y)
you can write this as such:

public static float divide(int x,int y){
 
   float fX = x;

   return  fX/y;
}

and that will work, but two lines ? Really ? naaah, we can do better than that.
we can use casting:

public static float divide(int x,int y){
   return (float)x/y;
}

And you say "Tada it's working now" you'll say, and you will be right (for java 1.8 at least)
but it's a bit ambiguous, what are you casting exactly the result? the left operand ? it's unclear so lets
fix it up to the final result.

public static float divide(int x,int y){
   return  ((float)x)/y;
}

In this example we are sure that the x will be float and it's a readable code

Seemed simple in the start, but look how complicated it has become.

Hope that helps anybody