03_ What is wrong with this code_ Data types & equals( ) Vs, hashCode( ) contract _ 800+ Big Data & Java Interview FAQs
03_ What is wrong with this code_ Data types & equals( ) Vs, hashCode( ) contract _ 800+ Big Data & Java Interview FAQs
ong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs
Home › Quick Prep Java Interview › 150+ Java coding Q&As › Coding - What is wrong? › 03: What is wrong
with this code? Data types & equals( ) Vs, hashCode( ) contract
Posted on April 25, 2015 100+ Java code quality Q&As
150+ Java coding Q&As
Q6. What is wring with this code?
12 }
13
1 import java.math.BigDecimal;
2
3 public static void main(String[] args) {
4 BigDecimal sum = BigDecimal.ZERO;
5 while (sum.compareTo(BigDecimal.ONE) != 0) {
https://www.java-success.com/part-2-beginner-what-is-wrong-with-this-java-code/ 1/7
06/12/2024, 19:37 03: What is wrong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs
6 sum = sum.add(BigDecimal.valueOf(0.1)); 800+ Enterprise & Core
7 } Java Q&As
8 System.out.print("The sum is: "+sum); //The sum is:
9 }
300+ Core Java Q&As
10
11 300+ Enterprise Java Q&As
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.
1 import java.util.Set;
2 import java.util.concurrent.CopyOnWriteArraySet;
3
4 public class WhatIsWrong {
5
6 public static void main(String args[]) {
7
8 Set<Person> people = new CopyOnWriteArraySet<>();
9 people.add(new Person("John", 35));
10 people.add(new Person("John", 32));
11 people.add(new Person("Simon", 30));
12 people.add(new Person("Shawn", 30));
13
14 System.out.println(people);
https://www.java-success.com/part-2-beginner-what-is-wrong-with-this-java-code/ 2/7
06/12/2024, 19:37 03: What is wrong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs
15
16 Person search = new Person("John", 35);
17
18 if (people.contains(search)) {
19 System.out.println("found: " + search);
20 } else {
21 System.out.println("not found: " + search);
22 }
23
24 }
25
26 //inner class
27 static class Person {
28
29 private String name;
30 private Integer age;
31
32 public Person(String name, Integer age) {
33 this.name = name;
34 this.age = age;
35 }
36
37 // getters and setters
38
39 @Override
40 public String toString() {
41 return "Person [name=" + name + ", age=" + age +
42 }
43 }
44
45 }
46
47
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.
https://www.java-success.com/part-2-beginner-what-is-wrong-with-this-java-code/ 3/7
06/12/2024, 19:37 03: What is wrong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs
1 // inner class
2 static class Person {
3
4 private String name;
5 private Integer age;
6
7 public Person(String name, Integer age) {
8 this.name = name;
9 this.age = age;
10 }
11
12 // getters and setters
13
14 @Override
15 public String toString() {
16 return "Person [name=" + name + ", age=" + age +
17 }
18
19 @Override
20 public int hashCode() {
21 final int prime = 31;
22 int result = 1;
23 result = prime * result + ((age == null) ? 0 : ag
24 result = prime * result + ((name == null) ? 0 : n
25 return result;
26 }
27
28 @Override
29 public boolean equals(Object obj) {
30 if (this == obj)
31 return true;
32 if (obj == null)
33 return false;
34 if (getClass() != obj.getClass())
35 return false;
36 Person other = (Person) obj;
37 if (age == null) {
38 if (other.age != null)
39 return false;
40 } else if (!age.equals(other.age))
41 return false;
42 if (name == null) {
43 if (other.name != null)
44 return false;
45 } else if (!name.equals(other.name))
46 return false;
47 return true;
48 }
49 }
50
Output:
https://www.java-success.com/part-2-beginner-what-is-wrong-with-this-java-code/ 4/7
06/12/2024, 19:37 03: What is wrong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs
‹ 01: What is wrong with following Java code snippets? Auto-unboxing, switch, short circuit &
exception
04: What is wrong with this code? Java Collection & ConcurrentModificationException ›
Arulkumaran Kumaraswamipillai
Mechanical Engineer to self-taught Java engineer in 1999. Contracting since 2002 as a Java Engineer &
Architect and since 2016 as a Big Data Engineer & Architect. Preparation & key know-hows empowered me
to attend 150+ job interviews, choose from 130+ job offers & negotiate better contract rates. Author of the
book "Java/J2EE job interview companion", which sold 35K+ copies & superseded by this site with 3.5K+
registered users Amazon.com profile | Reviews | LinkedIn | LinkedIn Group | YouTube Email: java-
[email protected]
"You are paid to read & write lots of code & solve business problems in a
collaborative environment"
100+ Free Java Interview FAQs
100+ Free Big Data Interview FAQs
Don't be overwhelmed by the number of Q&As. Job interviews are not technical contests to see who gets most number of questions right.
Nobody knows everything. The Clarity of the answers you give with real-life examples will go a long way in getting you multiple job offers.
It pays to brush-up & choose from 2-6 job offers. Experienced interviewers can easily judge your real experience from a few open-ended
questions & the answers you provide.
1. Feeling stagnated?
2. How to earn more?
3. Freelancing Vs contracting?
4. Self-taught professional?
5. Job Interview Tips
6. Resume Writing Tips
https://www.java-success.com/part-2-beginner-what-is-wrong-with-this-java-code/ 5/7
06/12/2024, 19:37 03: What is wrong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs
300+ Big Data Interview Q&As with code, scenarios & FAQs
100+ SQL Interview Q&As 01. 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code? 02.…
(2,425)
00: Top 50+ Core Java interview questions & answers for 1 to 3 years experience
Top 50 core Java interview questions covering core Java concepts with diagrams, code, examples, and scenarios. If you don't get…
(1,971)
Java 8 String streams and finding the first non repeated character with functional programming
Q1.Find the first non repeated character in a given string input using Java 8 or later? A1.Extends Find the first…
(1,669)
Membership Levels
Membership prices listed below are in Australian Dollars (A$). If you purchase in other currencies like Indian rupees, the equivalent…
(718)
0: 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code?
This extends 18+ SQL best practices & optimisation interview Q&As. You can practice these SQLs by setting up the data…
(370)
https://www.java-success.com/part-2-beginner-what-is-wrong-with-this-java-code/ 6/7
06/12/2024, 19:37 03: What is wrong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs
Java Collection interview questions and answers and Java String class interview questions and answers are must know for any Java…
(357)
Disclaimer
The contents in this Java-Success are copyrighted and from EmpoweringTech pty ltd. The EmpoweringTech pty ltd has the right to correct or enhance the current content without
any prior notice. These are general advice only, and one needs to take his/her own circumstances into consideration. The EmpoweringTech pty ltd will not be held liable for any
damages caused or alleged to be caused either directly or indirectly by these materials and resources. Any trademarked names or labels used in this blog remain the property of
their respective trademark owners. Links to external sites do not imply endorsement of the linked-to sites. Privacy Policy
© 2024 800+ Big Data & Java Interview FAQs Responsive WordPress Theme powered by CyberChimps
https://www.java-success.com/part-2-beginner-what-is-wrong-with-this-java-code/ 7/7