Search code examples
javatypescastingfloating-pointdouble

Java: double vs float


In another Bruce Eckel exercise, the code I've written takes a method and changes value in another class. Here is my code:

class Big {
  float b;
}

public class PassObject {
  static void f(Letter y) {
    y.c = 'z';
  } //end f()
  static void g(Big z) {
    z.b = 2.2;
  }

  public static void main(String[] args ) {
    Big t = new Big();
    t.b = 5.6;
    System.out.println("1: t.b : " + t.b);
    g(x);
    System.out.println("2: t.b: " + t.b);
  } //end main
}//end class

It's throwing an error saying "Possible loss of precision."

PassObject.java:13: possible loss of precision
found: double
required : float   z.b = 2.2
passobject.java:20: possible loss of precision
found : double
required : float   t.b = 5.6

Can't doubles be floats as well?


Solution

  • Yes, but you have to specify that they are floats, otherwise they are treated as doubles:

    z.b = 2.2f
    

    The 'f' at the end of the number makes it a float instead of a double.

    Java won't automatically narrow a double to a float.