This week's book giveaway is in the Server-Side JavaScript and NodeJS forum.
We're giving away four copies of Micro Frontends in Action and have Michael Geers on-line!
See this thread for details.
Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

comparing two objects by overriding equals and hashCode

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I have one class BillingAddress and it has overriden equals method to compare two bojects of it.

But when I pass null to BillingAddress obj2 = new BillingAddress(null, "Kumar"); it throws NULL POINTER EXCEPTION. Apparently, first names are different;one is null
another one has value john; Why does it throw exception and how do i fine tune it? i cant check for null pointer exception ,but it not right way of comparing two values.i should expect null also in one of the elements at run time. It should not throw null pointer exception.


please help me out.



 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exceptions show the line on which the exception happens. Just output the values used on that line
and add you'll see the value which caused the NullPointerException.

In this case it is:
(billingAddress.firstName).equals()
 
Marshal
Posts: 70373
283
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your class is inappropriately named; it has nothing to do with bills, nor addresses. It is a Name class.
Are you allowing null values for first name? I don't think you ought to. But if you do, you will have to allow for them in the equals() method. Note you have a mistake about the boolean value in the equals method, too. You should be comparing the two values with the == operator first. Also use the override annotation. Also check whether obj is null. Note you have to do these checks in the correct order.I write about equals methods often enough; there are three useful links in this post.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic