0% found this document useful (0 votes)
1 views

03_ What is wrong with this code_ Data types & equals( ) Vs, hashCode( ) contract _ 800+ Big Data & Java Interview FAQs

The document discusses common issues in Java code related to data types, equality checks, and the hashCode contract. It highlights problems such as infinite loops when using floating-point comparisons, rounding issues with monetary calculations, and the necessity of overriding equals() and hashCode() methods for proper object comparison in collections. The document provides examples and solutions to these issues, emphasizing best practices for Java programming.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

03_ What is wrong with this code_ Data types & equals( ) Vs, hashCode( ) contract _ 800+ Big Data & Java Interview FAQs

The document discusses common issues in Java code related to data types, equality checks, and the hashCode contract. It highlights problems such as infinite loops when using floating-point comparisons, rounding issues with monetary calculations, and the necessity of overriding equals() and hashCode() methods for proper object comparison in collections. The document provides examples and solutions to these issues, emphasizing best practices for Java programming.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

06/12/2024, 19:37 03: What is wrong with this code?

ong with this code? Data types & equals( ) Vs, hashCode( ) contract | 800+ Big Data & Java Interview FAQs

800+ Q&As Menu Contact & reviews Register Login

800+ Big Data & Java Interview FAQs


It pays to prepare & choose from 2-6 offers. Read & Write more code to fast-track & go places with confidence.

Select A to Z of Java & Big Data Techs


search here … Go

Home Why?  Career  Membership 

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

03: What is wrong with this 300+ Java Interview


Q&As - Quick Prep FAQs

code? Data types & equals( ) 300+ Java Interview FAQs 📌 

Vs, hashCode( ) contract 150+ Spring & Hibernate


FAQs
150+ Java Architect FAQs 📌


 Posted on April 25, 2015 100+ Java code quality Q&As

150+ Java coding Q&As

Q6. What is wring with this code?

1 public class WhatIsWrong {


2 300+ Big Data Interview
3 public static void main(String args[]) { Q&As - Quick Prep FAQs
4
5 float sum = 0; 300+ Big Data Interview
6 while (sum != 1.0) { FAQs 📌 
7 sum += 0.1;
8 }
250+ Scala Interview FAQs 
9 System.out.print("The sum is: "+sum); 250+ Python interview
10
11 }
FAQs 📌 

12 }
13

Key Areas & Companion


A6. Infinite loop at due to sum != 1.0. Using floating point variables
Techs FAQs
like float or double in loops to compare for equality can lead to
infinite loops. Comparing for “>” or “<" can cause precision issues. A 16+ Tech Key Areas FAQs 
better approach is
10+ Companion Tech Q&As 

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 

Q7. What is wring with this code?

Java & Big Data Tutorials


1 import java.math.BigDecimal;
2 Tutorials - Golang 
3 public class WhatIsWrong {
4
Tutorials - Big Data 
5 public static void main(String args[]) { Tutorials - Enterprise Java 
6
7 System.out.println(1.05 - 0.42); //1
8 System.out.println(new BigDecimal("1.05").subtract(ne
9 System.out.println(new BigDecimal(1.05).subtract(new
10 System.out.println(BigDecimal.valueOf(1.05).subtract(
11 System.out.println(105 - 42); //5
12
13 }
14 }
15
16

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?

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

A8. The output will be

1 [Person [name=John, age=35], Person [name=John, age=32], Perso


2 not found: Person [name=John, age=35]

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

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:

1 [Person [name=John, age=35], Person [name=John, age=32], Perso


2 found: Person [name=John, age=35]
3

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 ›

About Latest Posts

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]

How to take the road less travelled?


Practicing & brushing up a few Q&As each day on broad number of main stream categories can make a huge impact in 3-12
months.

"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.

If you are pressed for time, popular categories are pinned 📌


for you to prioritise based on the job description. Here are my top career
making know-hows & tips to open more doors as a Java/Big Data Engineer, Architect or Contractor.

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

Top 12 popular posts last 30 days


300+ Java Interview Q&As with code, scenarios & FAQs
300+ Core Java Interview Q&As 01. Ice breaker Tell us about yourself? 02. Ice Breaker 8 Java real life scenarios…
(6,825)

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)

18 Java scenarios based interview Q&As for the experienced – Part 1


Let's look at scenarios or problem statements & how would you go about handling those scenarios in Java. These scenarios…
(1,541)

Membership Levels
Membership prices listed below are in Australian Dollars (A$). If you purchase in other currencies like Indian rupees, the equivalent…
(718)

30+ Java Code Review Checklist Items


This Java code review checklist is not only useful during code reviews, but also to answer an important Java job…
(524)

8 real life Java scenarios with Situation-Action-Result (i.e. SAR) technique


The SAR (Situation-Action-Result) technique is very useful to tackle open-ended questions like: 1. What were some of the challenges you…
(522)

01: 30+ Java architect interview questions & answers – Part 1


One of the very frequently asked open-ended interview questions for anyone experienced is: Can you describe the high-level architecture of…
(480)

15 Ice breaker interview Q&As asked 90% of the time


Most interviews start with these 15 open-ended questions. These are ice breaker interview questions with no right or wrong answers…
(412)

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)

02: 10 Java String class interview Q&As

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

You might also like