A
PRO
2 days ago
Azcountry asked

Why does dividing an integer with integer not give a double type result? Here's the type of code I'm talking about: int number = 12; int result = number / 8; System.out.println(result);

Anuj Shrestha
Expert
2 days ago
Anuj Shrestha answered

Hi Az! That’s a great question, and I really like your mindset of trying to understand why things behave the way they do. This approach is very important when learning programming, keep it up.

To answer your question, in Java, the data types of the operands used in an operation determine how the calculation is performed.

In this code:

class Main {
    public static void main(String[] args) {

        int number = 12;
        int result = number / 8;
        System.out.println(result);
    }
}

Both number and 8 are of type int. Because of this, Java performs integer division.

Integer division removes the decimal part, so 12 / 8 is evaluated as 1, which is why the output is 1.

Even if you store the result in a double, the calculation still happens using integers:

int number = 12;
double result = number / 8;
System.out.println(result); // prints 1.0

Here, the division produces 1 first, and then Java converts it to 1.0 when assigning it to the double.

To get a decimal result like 1.5, at least one operand must be a double before the division and data type of variable used as result should be double too:

class Main {
    public static void main(String[] args) {

        int number = 12;
        double result = number / 8.0;
        System.out.println(result); // 1.5
    }
}

Here, 8.0 is a double, so Java uses floating-point division and preserves the decimal value.

Hope that helps. Feel free to reply here or in any other topics if you have doubts.

Java
This question was asked as part of the Learn Java Basics course.