Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why this output?

 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

Thanks in advance,
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello. Why is the third false?
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
and then added to 3.0d
Try this code and the difference will become apparent:
System.out.println((1.0f / 3.0f));
System.out.println((1.0d / 3.0d));

- Ortimus
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic