Double Division in Java

Haider Ali Oct 12, 2023
Double Division in Java

Here, in this guide, we will clear the confusion that occurs in the double division in Java. To understand that fully, we need to be familiar with data types in Java. Take a look at the following rules.

  1. Any arithmetic operation in between two integers will give an integer as an output.
  2. Any arithmetic operation in between integer and double will give out a double value.

You can say that data type double has higher precedence than an integer, so any operation involving double and integer will give a double value.

Integer-Double Division in Java

Take a look at the following code.

import java.util.*;
import javax.naming.spi.DirStateFactory.Result;
public class Main {
  public static void main(String args[]) {
    int x = 8;
    int y = 30;
    double z = y / x;
    System.out.println(z);
  }
}

What do you think this program will give as an output? 3.0 or 3.75. It will be 3.0 because we are simply dividing two integers, giving an integer as output, in this case, 3. We stored this output in double z, and it became 3.0 as the data type is double.

So, we need to apply casting to have a precise output that the following code can do.

import java.util.*;
import javax.naming.spi.DirStateFactory.Result;
public class Main {
  public static void main(String args[]) {
    int x = 8;
    int y = 30;
    double z = (double) y / x;
    System.out.println(z);
  }
}

Output:

3.75

Here, (double) is used for type casting in Java. So, both y and x became double. After division, the output will be double storing again z, which is also a double. So, the output will be 3.75.

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

Related Article - Java Math