Search code examples
javacompilationjavac

Compile with javac and convert double to float


Is it possible to set an compile option to compile this directly:

float f = 1.0;

I do not like to add the 'f' or 'F' after the '1.0'. So, can I tell the compiler to convert the double directly into a float?

Thank you for every answer.


Solution

  • No, there is no such option in the Java compiler. It would create a slightly different, incompatible dialect of the Java programming language - which has been avoided up until now.

    Generally speaking, the Java compiler and JVM are pretty strict in how they treat the language. There are very, very few options that can affect the behavior of source code at compile time or the logic at run time.

    For example, these are options that do not exist in Java (but may exist in other languages):

    • Make compilation case-insensitive.
    • Run the C preprocessor on Java source code (for macros, includes, etc.).
    • Skip all array index checks at run time.
    • Throw an exception on int overflow.

    The options that do exist are rather mundane:

    • Java compiler: Language version for the source code.
    • Java compiler: Character set of source file.
    • JVM memory limits.
    • JVM garbage collection algorithm tuning.

    As a side note, some compile-time behaviors are even mandated by the Java Language Specification. For example, certain types of unreachable code are compile-time errors, and a compliant Java compiler must flag it as an error (not as a warning or ignore):

    while (true) { ... }
    foo();  // Compile-time error
    

    Second example:

    return;
    bar();  // Compile-time error
    

    (This contrasts with C/C++, where unreachable code detection is an optional diagnostic provided by compilers to help a programmer; it is not required behavior.)