• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

output

 
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What is the output of trying to compile and run the following code?
(Select one correct answer)
-----------------------------------------------------------------------
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
}
}
-----------------------------------------------------------------------
A: false true false true
B: true false false true
C: false true true false
D: true false true false

The answer is A. Can someone explain why?
Thanks
Sunita Sridhar.
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Some importants things to remember:
a) integer arithmetic will yield an integer not a float-point number. Thus 1/3 is 0, not 0.33333
b) It is not possible to mix precission of float and double operands. Because the number of decimal digits are different for a float that for a double the operation can produce unexpected results. For instance: 1.0f / 3.0f * 3.0d is not 1, but a number very near to it. Thus all the float-point operands must be either float or double.
Applying these points to the example A is correct.
 
sun par
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jose
 
look! it's a bird! it's a plane! It's .... a teeny tiny ad
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic