• 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

Confusing outputs

 
Ranch Hand
Posts: 464
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test041
{
static double d;
static float f;
public static void main(String args[])
{
compare(Long.MAX_VALUE, Long.MAX_VALUE );
compare(Integer.MAX_VALUE, Integer.MAX_VALUE );
compare(Character.MAX_VALUE, Character.MAX_VALUE);
compare(Short.MAX_VALUE, Short.MAX_VALUE );
compare(Byte.MAX_VALUE, Byte.MAX_VALUE );
}
static void compare(double d, float f)
{
if (f == d) System.out.print(" equal" );
else System.out.print(" unequal");
}
}

Ans choices:
A: unequal equal equal equal equal
B: equal unequal equal equal equal
C: equal equal unequal equal equal
D: equal equal equal unequal equal
E: equal equal equal equal unequal
Ans: B???
Confusing?
Can some one help me please?
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ragu,
The problem comes from the argument conversion in the compare method invocation. I've added some lines in the code to show you why it is so...
public class Test
{
static double d;
static float f;
public static void main(String args[])
{
compare(Long.MAX_VALUE, Long.MAX_VALUE );
compare(Integer.MAX_VALUE, Integer.MAX_VALUE );
compare(Character.MAX_VALUE, Character.MAX_VALUE);
compare(Short.MAX_VALUE, Short.MAX_VALUE );
compare(Byte.MAX_VALUE, Byte.MAX_VALUE );
}
static void compare(double d, float f)
{
System.out.println("double="+d);
System.out.println("float="+f);
if (f == d) System.out.println(" equal" );
else System.out.println(" unequal");
}
}
Output:
double=9.223372036854776E18
float=9.223372E18
equal
double=2.147483647E9
float=2.14748365E9
unequal
double=65535.0
float=65535.0
equal
double=32767.0
float=32767.0
equal
double=127.0
float=127.0
equal
Now you can see that MAX_INT converted to Double and MAX_INT converted to Float are not quite the same...
Hope that helps,
Val
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic