Training Java – part 8 – result float and double type in divided calculation

How result give you divided two numbers?

I explain it on basic example:

public class Test {
public static void main(String[] ar )
double x1 = 1000/3;
float y1 = 1000/3;  
System.out.println("1000/3 : double x1= "+x1+", float y1 = "+y1);

double x2 = 1000.0/3;
float y2 = 1000.0f/3;  
System.out.println("1000.0/3: double x2 = "+x2+",1000.0f/3: float y2 = "+y2);

double x3 = 10.0/3;
float y3 = 10.0f/3;  
System.out.println("10.0/3: double x3 = "+x3+",10.0f/3: float y3 = "+y3);

double x4 = 10.0/3.0;
float y4 = 10.0f/3.0f;  
System.out.println("10.0/3.0: double x4 = "+x4+",10.0f/3.0f: float y4 = "+y4);


In first calculation the values are int type. So after calculate the result int divided by int is int. So 1000/3 will be 333. If it is as double result or float result the value will be with fractional part: 333.0.

In second and third or fourth calculation the first number is double or float, so result is this type. Therefore  result has more fractional digits: for double is more(max 15), for float is less(max 7).

Notice that you can not write:

float y2 = 1000.0/3; 

It is error.

Exception in thread "main" java.lang.RuntimeException: 
Uncompilable source code - incompatible types: 
possible lossy conversion from double to float

Why? Because double divided by int give you double, not float. Float must be sign will f letter.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.