03: What is wrong with this code? Data types & equals( ) Vs, hashCode( ) contract

Q6. What is wring with this code?

A6. Infinite loop at due to sum != 1.0. Using floating point variables like float or double in loops to compare for equality can lead to infinite loops. Comparing for “>” or “<" can cause precision issues. A better approach is

Q7. What is wring with this code?

A7. In the above code, //2, //4, and //5 are correct and //1 and //3 are incorrect usage leading to rounding issues. //3 is wrong due to incorrect usage of BigDecimal. So, either use BigDecimal properly as shown in //2 and //4, or use the smallest monetary value like cents with data type long as shown in //5. The cents approach performs better, and handy in applications that have heavy monetary calculations. Never use a floating point variable like float or double for monetary claculations. As they cause rounding issues as shown in //1.

Q8. What is wring with this code?

A8. The output will be

Q. Why is the person not found even though that person is there in the collection?
A. Every Java object implicitly extends the Object class, which has the default implementation of equals(…) and hashCode( ) methods. The equals(…) method is implicitly invoked by the Set class’s contains(…) method. In this case the default implementation in the Object class performs a shallow comparison of the references, and not the actual values like name and age. The equals and hashCode methods in Java are meant for overridden for POJOs. So, this can be fixed as shown below by overriding the equals and hashCode methods in Person.

After adding “hashCode()” and “equals(Object obj)” methods


Java & Big Data Interview FAQs

Java Key Areas Interview Q&As

800+ Java Interview Q&As

Java & Big Data Tutorials