The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion. The conversion from double to int is called explicit conversion or narrowing conversion.

We know that the double data type can contain decimal digits. The decimal digits are truncated when we convert double value with decimal digits to int value.

Double value can contain decimal digits, so when we convert double value with decimal digits to int value, the decimal digits are truncated. There are two ways to convert double to int.

  • Using Typecasting
  • Using intValue() method

Using Typecasting

Typecasting is used to perform the conversion between two incompatible types. Typecast operator (data type) is used to perform typecasting in Java. The signature of typecasting is:

Example

In the following example, we have taken a variable pi of type double and initialized the value of pi 3.14159265359 to it. pi2 is a variable of type int which stores the converted value of pi. (int) is a typecast operator. pi is a variable which we want to convert into int type. The first println statement prints the pi value before truncation of decimal digits. The second println statement prints the pi value after truncation of decimal digits.

Output

Using intValue() method

The intValue() is the built-in method of Integer wrapper class which belong to the java.lang package. It does not accept any parameter. It returns the value which is represented by the object after conversion to int type. Double wrapper class truncates all digits after the decimal point.

Example

In the following example, Double is a wrapper class, and d is an object of Double class. The new is a keyword that creates an object dynamically.  Double() automatically calls the constructor of Double class. The constructor parses a double value as an argument. We have taken another variable i of type int which stores the converted int value. The object d invokes the intValue() method of Integer class, and converts double type into int type. The first println statement prints the value before truncation. The second println statement prints the value after truncation.

Output

Pin It on Pinterest

Share This