Originally posted by Sweta Pillai:
1->OK
2->OK o/p =10.000000
3->java.util.IllegalFormatConversionException: f != java.lang.Integer
4->OK o/p =10.000000
5->Not OK (Type mismatch: cannot convert from double to float-No issue)
The question is: while 1 compiles, 5 doesn't. Ok. But while 3 causes exception, 4 using 10.0 does fine. Why this contrast between normal float usage and in format()/printf() ? I mean 10.0 acceptable in one case, while the same is not acceptable in other.
1 compiles because in
Java, an int, which is the default type of 10, can be automatically promoted to a float.
However, 5 does not compile, because a double, which is the default type of 10.0, cannot be assigned to a float without an explicit cast.
In the format
string, %f means a floating point number. So in 3, System.out.printf is expecting a float or a double. Since the type of the parameters of System.format are Object, primitives will be boxed to their corresponding wrapper classes. There is no relationship between Integer and Float or Integer and Double.
In 4, 10.0 is a floating point number so System.out.printf with a %f in the format string will accept 10.0.