Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Uncomparable Puzzles in Java

DZone's Guide to

Uncomparable Puzzles in Java

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

This is a few puzzles for you to solve in Java.

b == a is true
(long) b < a is true

d < c is true
d < (long) c is false

e <= f is true
e >= f is true
e == f is false

x == y is false
x.doubleValue() == y.doubleValue() is true
x.equals(y) is false
x.compareTo(y) == 0 is true
See if you can work out why this code produces the output above (if you use StackOverflow, I will know ;)
long a = (1L << 54) + 1;
double b = a;
System.out.println("b == a is " + (b == a));
System.out.println("(long) b < a is " + ((long) b < a));

double c = 1e19;
long d = 0;
d += c;
System.out.println("\nd < c is " + (d < c));
System.out.println("d < (long) c is " + (d < (long) c));

Double e = 0.0;
Double f = 0.0;
System.out.println("\ne <= f is " + (e <= f));
System.out.println("e >= f is " + (e >= f));
System.out.println("e == f is " + (e == f));

BigDecimal x = new BigDecimal("0.0");
BigDecimal y = BigDecimal.ZERO;
System.out.println("\nx == y is " + (x == y));
System.out.println("x.doubleValue() == y.doubleValue() is " + (x.doubleValue() == y.doubleValue()));
System.out.println("x.equals(y) is " + x.equals(y));
System.out.println("x.compareTo(y) == 0 is " + (x.compareTo(y) == 0));
A solution will be posted this week.


Bonus puzzle:  The Shrinking collections.
List<BigDecimal> bds = Arrays.asList(new BigDecimal("1"), 
    new BigDecimal("1.0"), new BigDecimal("1.00"), BigDecimal.ONE);
System.out.println("bds.size()=    " + bds.size());
Set<BigDecimal>bdSet = new HashSet<>(bds);
System.out.println("bdSet.size()=  " + bdSet.size());
Set<BigDecimal>bdSet2 = new TreeSet<>(bds);
System.out.println("bdSet2.size()= " + bdSet2.size());
prints
bds.size()=    4
bdSet.size()=  3
bdSet2.size()= 1

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:

Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}