Win a copy of Design for the Mind this week in the Design forum!

# why this output?

Vishy Karl
Ranch Hand
Posts: 116
Hi All,
Why is the following o/p correct for fol. statement. ?
System.out.print((1 - 1 / 3 * 3 ==0)+" "); //1
System.out.print((1 - 1.0f / 3.0f * 3.0f==0)+" "); //2
System.out.print((1 - 1.0f / 3.0f * 3.0d==0)+" "); //3
System.out.print((1 - 1.0d / 3.0d * 3.0d==0)+" "); //4
Correct Ans is
A: false true false true

Jessica Sant
Sheriff
Posts: 4313

The 1st one is false because those numbers are integers. So the decimal are stripped off and you're left with just the integer when you do division.
So.... the problem breaks down like this
1 - ( 1/3 ) * 3 == 0
1 - ( 0 ) * 3 == 0
1 - 0 == 0
1 == 0
false
#'s 2,3,4 behave as you'd expected because the numbers are floating points. so 1.0/3.0 == 0.333333

dennis zined
Ranch Hand
Posts: 330
Hello. Why is the third false?

Ranch Hand
Posts: 170
Hi,
I think the expression involving multiplication and division makes the difference.
class a
{
public static void main(String args[])
{
//System.out.print((1-1.0d / 3.0d * 3.0d)==0);
//System.out.print((1 - 1.0f / 3.0f * 3.0f==0)+" ");
//System.out.print((1 - 1.0f / 3.0f * 3.0d==0)+" ");
System.out.println( "float double"+1.0f / 3.0f * 3.0d); //line 1
System.out.println( "double only"+1.0d / 3.0d * 3.0d); //line 2

}
}
Line1 gives an output of 1.0000000298023224
Line 2 gievs an output of 1.0.

Why is this happening? I was thinking that both the expression would evaluate to double .

Sumitro Palit
Ranch Hand
Posts: 37
Lakshmi,
System.out.println(1.0f / 3.0f * 3.0d);
is the same as
System.out.println((1.0f / 3.0f) * 3.0d);

The result of 1.0f/3.0f is a float, which is promoted to a double