• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

equals() K&B

 
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can any one explain wat exactly is being compared at lines 1,2,3,4
and hence why the result if we put System.out.println after each of these lines

public class WrapTest
{
public static void main(String [] args)
{
int result=0;
short s =42;
Long x= new Long("42");
Long y=new Long(42);
Short z=new Short("42");
Short x2=new Short(s);
Integer y2=new Integer("42");
Integer z2 = new Integer(42);

//1 if(x==y) result=1;
//2 if(x.equals(y)) result = result +10;
//3 if(x.equals(z)) result = result +100;
//4 if(x.equals(x2)) result = result +1000;
System.out.println("result = " +result);
}
}
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
== is a simple comparison of values (references), so A == B is true if A and B both reference the same object.

As for the equals method, have you checked the API description for equals in the java.lang.Long?
 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here
== stands for Object reference equality &
.equals(Object o) stands for Object value equality

Now u r question
//1 if(x==y) result=1;
Here references x & y are compared. Since these r 2 diff objects. x==y is false
//2 if(x.equals(y)) result = result +10;
Here values of x & y are compared.Both r 42 so x.equals(y) is true
//3 if(x.equals(z)) result = result +100;
Here also values of x & z are compared.Both r equal i.e 42, but x is Long while z is short.So x.equals(z)) is false
//4 if(x.equals(x2)) result = result +1000;
Here values of x & x2 r compared.Both r equal i.e 42, but x is Long while x2 is short.So x.equals(x2)) is false
 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Swathi for the explanation,

even i thought of the same explanation but had a doubt...

thanks again
reply
    Bookmark Topic Watch Topic
  • New Topic