double to int Java


After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast double to int.

By memory-wise, double takes 8 bytes of memory and int take 4 bytes of memory. Assignment of 8 bytes value to a 4 byte value requires explicit casting.

byte –> short –> int –> long –> float –> double

The left-side value can be assigned to any right-side value and is done implicitly. The reverse like long to short requires explicit casting. That is, Programmer should do himself casting (explicit).

Examples of implicit casting

int x = 10; // 4 bytes
double y = x; // 4 bytes to 8 bytes

byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes

Following program on double to long explains explicit casting. Observe,Java style where a double is assigned to an int.
public class Conversions
{
  public static void main(String args[])
  {
    double d1 = 10.5;           // 8 bytes
    // int i1 = d1;             // 8 bytes value to 4 bytes
          
    int i1 = (int) d1;          // 8 bytes value explicitly type casted to int of 4 bytes

    System.out.println("double value: " + d1);            // prints 10.5
    System.out.println("Converted int value: " + i1);     // prints 10, 0.5 gone
  }
}


double to int
Output screenshot of double to int Java

int i1 = d1;

The above statement raises a compilation error "possible loss of precision".

int i1 = (int) d1;

The double d1 is explicitly type casted to int i1. Observe, the syntax of explicit casting. On both sides, it should be int only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.