I have written a simple Java program as shown here:
public class Test {
public static void main(String[] args) {
int i1 =2;
int i2=5;
double d = 3 + i1/i2 +2;
System.out.println(d);
}
}
Since variable d
is declared as double I am expecting the result of this program is 5.4
but I got the output as 5.0
Please help me in understanding this.
When one operand is an int and the other is a double, Java creates a new temporary value that is the double version of the int operand. For example, suppose that we are adding dd + ii where ii is an int variable. Suppose the value of ii is 3. Java creates a temporary value 3.0 that is the corresponding double value.
int is a 32 bit data type which can be used to store integer. double is 64 bit data type used to store floating point numbers that is numbers which has something after decimal point.
Short answer is "no" - the range of values an int can represent and that a double can represent are implementation defined - but a double certainly cannot support every integral value in the range it can represent.
i1/i2
will be 0. Since i1
and i2
are both integers.
If you have int1/int2
, if the answer is not a perfect integer, the digits after the decimal point will be removed. In your case, 2/5
is 0.4, so you'll get 0.
You can cast i1
or i2
to double
(the other will be implicitly converted)
double d = 3 + (double)i1/i2 +2;
i1/i2
when converted to int gives 0. ie. why you are getting 5.0. Try this :
public static void main(String args[])
{
int i1 =2;
int i2=5;
double d = 3 + (double)i1/(double)i2 +2;
System.out.println(d);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With