About Question enthuware.ocpjp.v21.2.1724 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
giginar
Posts: 4
Joined: Fri Feb 07, 2025 5:36 pm
Contact:

About Question enthuware.ocpjp.v21.2.1724 :

Post by giginar »

"the implementation of compareTo methods of String, Integer, and Double classes are not compatible with each other and they throw ClassCastException when an object of one class is compared with an object of another class." this sentence in the explanation and actually the answer of the question, I strongly advice to add why they are not comparable to each other also. For example, Integer and Double are also not comparable when used together. The code group below would throw the same exception, too.

Object[] sa = { 100.1, 100.0, 100 };
Collections.sort(Arrays.asList(sa), null);
System.out.println(sa[0]+" "+sa[1]+" "+sa[2] );

Why is that exactly?

admin
Site Admin
Posts: 10389
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question enthuware.ocpjp.v21.2.1724 :

Post by admin »

Because Integer's compareTo method tries to cast the argument to Integer. If you try to invoke the compareTo method on an Integer object and pass it a Double object, then casting it to Integer will cause a ClassCastException to be thrown. The same happens for other classes also.

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests