Reputation: 61
public class Main
{
float fValue;
public static void main(String[] args) {
Main obj=new Main();
System.out.println(obj.fValue);
}
}
Here the output is 0.0 and not 0.0f.Can anyone explain it?
Upvotes: 1
Views: 1821
Reputation: 46
That's because the "f" used after a float's digits is actually used in creation time so as to mark the value as a float. Eg. The number 123.45f is a float as it has been marked by an "f". The number 123.45d is a double, as it is marked by "d". Example, see the two cases below
Instantiating a float variable
float floatVariable = 123.45f;
Passing a float variable to a method.
method declaration:
void printFloat(float floatValue){
System.out.println(floatValue);
}
method call:
printFloat(floatVariable);
printFloat(123.45f);
All values with decimal digits are by default double, and all numbers without decimal digits are by default integers. The "f" is required to declare the number as float.
printFloat((float)12345);
Above, you will have to cast to float because 12345
is an integer.
printFloat((float)123.45)
Above, you will have to cast to float because 123.45
is a double.
printFloat(123.45f);
Excellent!
At the other hand, printing the variable only prints the value. It is not a case of creation, so no necessary qualifier is needed.
Upvotes: 1