• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Question

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got this question given below from a mock exam and i m not able to understand its output.Can somebody explain why its output will be "false true false true".
import java.io.*;

public class T026
{

public static void main(String args[])
{
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
}
}
 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Here are the answers to ur queries:
The first statement,

1 - 1 / 3 * 3

will be evaluated as follows:
1 - (1/3) * 3 = 1 - (0 * 3) = 1 - 0 = 1.
This is because in integer arithmetic operations, the division operator (/) has highest precedence followed by the multiplication operator (*) followed by Addition and Subtraction. Hence //1 returns false.

1 - 1.0f / 3.0f * 3.0f


Again, the evaluation proceeds as 1 - (1.0f / 3.0f) * 3.0f = 1 - (0.3333333... * 3) = 1 - 1 = 0. Thus //2 returns true.

1 - 1.0f / 3.0f * 3.0d


The evaluation proceeds as 1 - (1.0f / 3.0f) * 3.0d. But here we have a floating point and a double value. So the floating point operation is performed first...then converted to double...1 - 0.33333d * 3.0d. But converting from floating point to double causes some loss of precision and hence the result is <> 0. Hence //3 returns false.

Finally,

1 - 1.0d / 3.0d * 3.0d


returns true as all operations are with double values. Reasoning is much the same as at //2

Hope u got ur answers ?

Correct me if I was wrong anywhere.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic