Because you are relying on autoboxing when you wrote

Object prova = 9.2;

If you want it to be a Float, try

Object prova = 9.2f;

Remember that java.lang.Float and java.lang.Double are sibling types; the common type is java.lang.Number

If you want to express a Number in whatever format, use the APIs, for example Number.floatValue()

Answer from Dilum Ranatunga on Stack Overflow
Discussions

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float
There was an error while loading. Please reload this page · Expected behavior java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float More on github.com
🌐 github.com
3
January 9, 2020
java - ClassCastException Double to Float even when I'm not using a Double - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
java - Possible lossy conversion from double to float, given float values? - Stack Overflow
if i'm not mistaken, "0.5" are decimal numbers; thus, making it a float value. but why is java telling me that it is a double?. the return statements are detected as errors by java, saying: "incomp... More on stackoverflow.com
🌐 stackoverflow.com
Convert double to float in Java - Stack Overflow
I am facing an issue related to converting double to float. Actually, I store a float type, 23423424666767, in a database, but when we get data from the database in the below code, getInfoValueNume... More on stackoverflow.com
🌐 stackoverflow.com
September 29, 2015
Top answer
1 of 3
2

You can fix this by adding @specialized(Float) to the A: ClassTag type parameter.

Here's a slightly simplified version of your code with the added @specialized(Float) tag. (I also added @specialized(Int) to make the example more complete.)

import scala.reflect.ClassTag

class Test[@specialized(Float, Int) A: ClassTag] {
  def apply(count: Int): Array[A] = Array.tabulate(count) { 
    i => (1.5 + i).asInstanceOf[A];
  }
}

val floatTest = new Test[Float];
println(floatTest(5).mkString(", ")); // 1.5, 2.5, 3.5, 4.5, 5.5
// Works because code is specialized for float
// and primitive double is cast to primitive float.

val doubleTest = new Test[Double];
println(doubleTest(5).mkString(", ")); // 1.5, 2.5, 3.5, 4.5, 5.5
// Works although code is not specialized for double
// but Double object can be cast to Double object.

val intTest = new Test[Int];
println(intTest(5).mkString(", ")); // 1, 2, 3, 4, 5
// Works because code is specialized for int
// and primitive double is cast to primitive int.

val longTest = new Test[Long];
println(longTest(5).mkString(", ")); // ClassCastException
// Fails because code is not specialized for long
// and Double object cannot be cast to Long object.
// Works if you add @specialized(Long).

(The no-op cast from Double object to Double object is called identity conversion.)

You can also omit the list of types from @specialized. In this case, the class will be specialized for all primitive types:

class Test[@specialized A: ClassTag] {
...

Be aware though that this will generate a lot more class files. For example, if all Scala collection classes would be specialized for all primitive types, the Scala language library would suddenly become about ten times as large.


The root problem is this: The casting rules for boxed primitives are very different from the casting rules for unboxed primitives.

In this case (using Java syntax):

double d = 1.0 / 5.0; // 0.2 as a double primitive value
float f = (float)d; // 0.2f as a float primitive value

Works as expected. The cast from double to float is known as narrowing primitive conversion.

But this doesn't work:

java.lang.Double d = 1.0 / 5.0; // 0.2, but in a java.lang.Double object
java.lang.Float f = (java.lang.Float)d; // ClassCastException

No narrowing or widening conversion from java.lang.Double to java.lang.Float is possible because neither is a subclass of the other, and boxing and unboxing conversions are not applied either. More precisely, there is an implicit boxing conversion from double to java.lang.Double in the first line, but no implicit boxing or unboxing conversion is applied in the second line.

Scala makes the issue even more confusing because it tries to hide the distinction - Scala only has type Double, but no type double. Depending on context, the Scala type Double is sometimes (I think most of the time) mapped to the Java primitive type double and sometimes to the Java reference type java.lang.Double.

2 of 3
1

This is actually a few leaky abstractions interacting. .asInstanceOf[A] doesn't become .asInstanceOf[Float] when A happens to be Float; it's really .asInstanceOf[Object] which gives you in this case a java.lang.Double. It has to be that way because there is just one class test, not a separate version for different As, and .asInstanceOf[Object] is a completely different operation from .asInstanceOf[Float] in JVM bytecode.

The cast to Float is added later and invisible in your code, and then java.lang.Double can't be cast to it (unlike a Double!).

I think the most reasonable way is defining a typeclass (Numeric is mentioned in the comments, but it doesn't have the method we want).

trait FromDouble[A] {
  def apply(x: Double): A
}
object FromDouble {
  implicit object DoubleFromDouble extends FromDouble[Double] {
    def apply(x: Double) = x
  }
  implicit object FloatFromDouble extends FromDouble[Float] {
    def apply(x: Double) = x.toFloat
  }

  // optional, to simplify test.arr a bit
  def applyA(implicit fromDouble: FromDouble[A]) = fromDouble(x)
}

class test[A : ClassTag : FromDouble] {
  private val arr: Array[A] = Array.tabulate(10){ x=>
    FromDoubleA / 5.0)
  }

  def apply(i: Int): A = arr(i)
}
🌐
Coderanch
coderanch.com › t › 731925 › java › Casting-int-double-failing
Casting int to double is failing (Beginning Java forum at Coderanch)
June 25, 2020 - Ken Austin wrote:The error messages seems to indicate that I am trying to convert a double to a float, but that's not the case. And yet, I see: Which is effectively trying to convert a double to a float. You probably need to either use doubles, or use floats.
🌐
GitHub
github.com › redisson › redisson › issues › 2531
java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float · Issue #2531 · redisson/redisson · GitHub
January 9, 2020 - Expected behavior java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Float Actual behavior No exception is thrown Steps to reproduce or test case @test public void testBucketFloat(){ String key = dcsConfigProperti...
Author: redisson
Top answer
1 of 4
13

If I'm not mistaken, 0.5 are decimal numbers; thus, making it a float value.

You should not rely solely on your intuition when learning a new programming language.

In fact, 0.5 is a double literal. For a float literal you need to write 0.5f.

As The Java Language Specification (JLS 3.10.2) states:

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d.

See also:

  • The Oracle Java Tutorial > Primitive Data Types
2 of 4
7

You have two options.

One is change your method's return type to double.

The other is change the double values you are returning to float values, as many have said in the comments.

public float typeDmgMultiplr(String type,String type2){
    if(type.equalsIgnoreCase("grass")){
        if(type2.equalsIgnoreCase("grass"))
            return 0.5f;
        else if(type2.equalsIgnoreCase("poison"))
            return 0.5f;
        else if(type2.equalsIgnoreCase("fire"))
            return 0.5f;
        else
            return 2.0f;
    }
    else if(type.equalsIgnoreCase("fire")){
        if(type2.equalsIgnoreCase("grass"))
            return 2.0f;
        else if(type2.equalsIgnoreCase("poison"))
            return 1.0f;
        else if(type2.equalsIgnoreCase("fire"))
            return 0.5f;
        else
            return 0.5f;
    }
    else if(type.equalsIgnoreCase("water")){
        if(type2.equalsIgnoreCase("grass"))
            return 0.5f;
        else if(type2.equalsIgnoreCase("poison"))
            return 1.0f;
        else if(type2.equalsIgnoreCase("fire"))
            return 2.0f;
        else
            return 0.5f;
    }
    else{
        if(type2.equalsIgnoreCase("grass"))
            return 2.0f;
        else if(type2.equalsIgnoreCase("poison"))
            return 0.5f;
        else if(type2.equalsIgnoreCase("fire"))
            return 1.0f;
        else
            return 1.0f;
    }

}
Find elsewhere
🌐
Esri Community
community.esri.com › t5 › arcgis-survey123-questions › new-error-class-java-lang-double-cannot-be-cast-to › td-p › 1104038
Solved: New Error class java.lang.Double cannot be cast to... - Esri Community
October 5, 2021 - Solved: Hello. A few days ago our calculation to prepopulate a field based on the default of another field and worked fine but now we get that java error that I
🌐
Oracle
docs.oracle.com › javase › specs › jls › se7 › html › jls-5.html
Chapter 5. Conversions and Promotions
September 15, 2026 - Second, it implies that it is permitted for a program to include redundant cast operators for the sake of clarity. 19 specific conversions on primitive types are called the widening primitive conversions: ... A widening primitive conversion does not lose information about the overall magnitude of a numeric value. A widening primitive conversion from an integral type to another integral type, or from float to double in a strictfp expression (§15.4), does not lose any information at all; the numeric value is preserved exactly.
Top answer
1 of 6
18

It would help if you provide a stacktrace.

Otherwise, the standard solution is to replace (Float) someLongValue with someLongValue.floatValue()

If you are dealing with primitive types, you can just cast from long to float, although it is a 5.1.2 Widening Primitive Conversion, but one that may lose precision, so be careful! Obviously you have the wrapper type Long, which cannot implicitly be converted, thus you get the classcastexception. This may be because of autoboxing, or explicit Long object creation.

Some more uninvited advice: if your valid values are decimals in the range of -10 to +10 the standard data type is int (primitive). avoid float if you mean exact numbers. long is also not optimal, because it is not fully atomic like int and it takes 2x the memory. If you allow a different state "not assigned" then Integer, which may take null, is also OK.

2 of 6
10

The exception happens because the compiler recognizes that Long and Float do not have a parent-child dependency. Unlike C++, which will try to find an overloaded cast operator.

You can call doubleValue() on any of the primitive wrapper types that are derived from Number, so this is the recommended way to do what you want:

double val = ((Number)textField.getValue()).doubleValue()

A couple of things to note here: first, I casted the output of getValue() to Number. That way, you can change your mind and actually return Double values in the future, and you won't break.

Also, I'm using double values, not float. The JVM works with double internally, so there's no reason to use float except to save space in an array.

🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-fix-java-lang-classcastexception-in-java
How to Fix java.lang.classcastexception in Java? - GeeksforGeeks
December 12, 2022 - Direct casting will not work and it throws ClassCastException. Instead, we can use · String.valueOf() method. It converts different types of values like int, long, boolean, character, float etc., into the string.
🌐
Rollbar
rollbar.com › home › how to handle the incompatible types error in java
Java Incompatible Types: Lossy Conversion From Double to Int
2 weeks ago - Javac raises this error when you assign a wider type like double to a narrower int. Fix it with an explicit (int) cast, shown in Java code examples.
🌐
YouTube
youtube.com › watch
incompatible types: possible lossy conversion from double to float - YouTube
To fix the Java error: incompatible types: possible lossy conversion from double to float, you should put the float type in parentheses next to the double va...
Published: November 17, 2024