Khaled Lela
Khaled Lela

Reputation: 8129

Java cast double to long exception

1- long xValue = someValue;

2- long yValue = someValue;

3- long otherTolalValue = (long)(xValue - yValue);

That line of code give me the following exception:

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Long.

code piece:

StackedBarChart<String,Number> sbc = new StackedBarChart<String,Number>();

XYChart.Series<String, Number> series = new XYChart.Series<String, Long>();
series.getData.add(new XYChart.Data<String, Number>("X1",150));
series.getData.add(new XYChart.Data<String, Number>("X2",50));
sbc.getData.add(series);
long dif = getDif(sbc);

long getDif(XYChart barChart){
XYChart.Series series = (XYChart.Series).getData().get(0);
// X1 at zero position i dont have to use iIterator now.
XYChart.Data<String, Long> seriesX1Data = series.getData().get(0);
XYChart.Data<String, Long> seriesX2Data = series.getData().get(1);

long x1Value = seriesX1Data.getYValue();
long x2Value = seriesX1Data.getYValue();
// line - 3 - exception on the next line
// -4- long value = (x1Value) - (x2Value);
long value = (long)(x1Value) - (long)(x2Value);
return value;
}

seriesX1Data,seriesX2Data contains double values as the passed chart has Number type but getYvalue() return long that is why program crash at runtime with that exception but when i cast in line why cast not succeed. i think that compiler see that the type already long !.

Upvotes: 1

Views: 10095

Answers (4)

boriswaguia
boriswaguia

Reputation: 41

I don't really understand why your code fail, but the following also works fine.

    public class CastingDoubleToLongTest {

      @Test
      public void testCast(){
        double xValue = 12.457;
        double yValue = 9.14;

        long diff = new Double(xValue - yValue).longValue();

        Assert.assertEquals(3, diff);
      }
   }

Upvotes: 1

GriffeyDog
GriffeyDog

Reputation: 8376

Presumably someValue is a double. To assign it to a long you need to cast it:

long xValue = (long) someValue;

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

It's impossible

long xValue = someValue;
long yValue = someValue;
long otherTolalValue = (long)(xValue - yValue);

neither of the 3 lines can produce java.lang.ClassCastException

Assuming someValues is Double,

Double someValue = 0.0;

it would give compile error: Type mismatch: cannot convert Double to long

Upvotes: 2

Matten
Matten

Reputation: 17631

long xValue = (long)someValue;
// or : 
long yValue = new Double(someValue).longValue();

long otherTolalValue = xValue - yValue;

But keep in mind that you will loose precision.

Upvotes: 3

Related Questions