Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java program using int and double

Tags:

java

int

double

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.

like image 545
chaitanya Avatar asked May 02 '13 09:05

chaitanya


People also ask

Can we add int and double in Java?

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.

What is int and double in Java?

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.

Can an int be a double?

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.


2 Answers

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;

like image 133
Maroun Avatar answered Nov 15 '22 05:11

Maroun


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);
        }
like image 21
Vineet Singla Avatar answered Nov 15 '22 06:11

Vineet Singla