EN
Java - how to cast Double object to primitive int?
11
points
1. Problem description
How to cast Double object to primitive int type?
Double num = 3.14; // original - Double object
int num = 3; // expected - primitive int
2. Solution with Double.intValue()
We can use Double.intValue()
method as it returns primitive int.
Code example:
Double num = 3.14;
int intValue = num.intValue();
System.out.println(intValue); // 3
Output:
3
3. Solution with casting
- Cast Double to primitive double
- Then cast primitive double to primitive int
Code example:
Double num = 3.14;
int intValue = (int) (double) (num);
System.out.println(intValue); // 3
Output:
3