• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

equals method for objects

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Outer{
public static void main(String args[]){

try {
if ((new Object()).equals((new Object()))) {
System.out.println("equal");
}else{
System.out.println("not equal");
}
}catch (Exception e) {
System.out.println("exception");
}
}
}
While running this program it shows the output is not equal.
Why ?I thought the vales in those are null values(These are eual)
Please explain?
 
Ranch Hand
Posts: 99
Mac Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Object class's equal() method is very shallow and uses == operator for equality check. The == operator checks whether the two object references are equal.

Since in your example, two different objects are created and checks, the equal() method returns false so giving the output "not equal".
 
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I thought the values in those are null values(These are equal)


there isn't any argumented constructor in Object class also doesn't have any instance variables..

so what exactly you mean by null values??


equals method in Object class only checks whether the two reference variables refer to the same object or not..
hence creating two objects of Object class with new operator will always return false...
 
Our first order of business must be this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic