-1

I want to know what happened when Double invert to int on my example?

this case is right

Double d = 123.13;
int i = (int)(Math.random()*d);

this case is wrong

Double d = 123.13;
int i = (int)(d);

enter image description here error message:Inconvertible types;cannot cast'java.lang.Double'to'int'

and I know I can use d.intValue to do this, but I just want to know what is the difference about the two situations above

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25

4 Answers4

3

A wrapper type can be cast only to the primitive type that it wraps.

i.e. you can cast a Double to a double, but not directly to an int.

The second snippet can pass compilation with:

Double d = 123.13;
int i = (int)(double)(d);

In the first snippet, you are casting a primitive (the type of Math.random()*d is double), to an int, which is allowed.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

You could cast the primitive value like this, too:

Double d = 123.13;
int i = (int) d.doubleValue();

…which is pretty much the same as the answer given by Eran.

deHaar
  • 17,687
  • 10
  • 38
  • 51
0

Situation 1: Double d = 123.13;int i = (int)(Math.random()*d);

Situation 2: Double d = 123.13;int i = (int)(d);

What is difference about the two situations above?

In the first case Math.random() returns a double, not Double, so this one is right because double can be cast to int (losing the fraction part).

Situation 2 is wrong and the reason is explained in @Eran's answer, A wrapper type can be cast only to the primitive type that it wraps. i.e you cannot cast Double to nonconvertible primitive int

0

There is lots of thing going on, see JLS 5.1.7. Boxing Conversion .

2nd one is wrong because Double is class and double is primitive data type

Narrowing is possible using primitive data type only

JLS 5.1.3. Narrowing Primitive Conversion

22 specific conversions on primitive types are called the narrowing primitive conversions:

short to byte or char

char to byte or short

int to byte, short, or char

long to byte, short, char, or int

float to byte, short, char, int, or long

double to byte, short, char, int, long, or float

So to your code to work you can change your code like below

double d = 123.13;
int i = (int)d;
Community
  • 1
  • 1
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89