in C language
float a=0.1;
if(a==.1)
printf("hello");
else
printf("123");
Output is 123
But for Java
float a=0.1F;
if(a==.1)
System.out.println("hello");
else
System.out.println("123");
Ans is hello
.
Why?
in C language
float a=0.1;
if(a==.1)
printf("hello");
else
printf("123");
Output is 123
But for Java
float a=0.1F;
if(a==.1)
System.out.println("hello");
else
System.out.println("123");
Ans is hello
.
Why?
Here comparison by ==
first converts float
to double
and than compares both value.
float real = 0.1f;
double real2 = real;
System.out.println(real2);
OUTPUT
0.10000000149011612
Now you can see when you convert float
to double
for value 0.1
you will not get the exact value here. Here system will convert your float
value to double
with extra precision in data.
Same thing happens here when you write if(a==.1)
your a
will be converted to something like 0.10000000149011612
and than compares with 0.1
which is already double
and has exact value 0.1
and so it result to false
and must print 123
and not hello
that I am sure about.
You're comparing apples and oranges. In the Java case, you should be using
if (a == 0.1F)