Operators

Equals

The "==" by default compares addresses of objects . It works well with primitive types but when we apply it to class objects we need to do a little bit of work.

File: "equals1.java"

class pet

{

String name ;

/* public boolean equals( Object obj1 )

{

pet pet1 = (pet)obj1 ;

return ( pet1.name.equals( name ) ) ;

} */

}

public class equals1

{

public static void main(String args[] )

{

pet object1 = new pet() ; object1.name = "Ginger" ;

pet object2 = new pet() ; object2.name = "Ginger" ;

if ( object1 == object2 )

System.out.println( "Equals with the == sign" ) ;

if ( object1.equals(object2) )

System.out.println( "Equals with the equals method." ) ;

}

}

Output:

[amittal@hills Operators]$ java equals1

[amittal@hills Operators]$

The first statement:

if ( object1 == object2 )

System.out.println( "Equals with the == sign" ) ;

The above will compare addresses because that's what object1 and object2 store and since they are 2 different objects the above statement does not return true.

All Java classes are derived from the class Object and this class has an "equals" method that we can call. However the Object method "equals" does the same thing by default and the statement return false.

if ( object1.equals(object2) )

System.out.println( "Equals with the equals method." ) ;

What we need is a customize method that tells us that the objects are equal of the names in our objects are equal.

File: "equals2.java"

class pet

{

String name ;

public boolean equals( Object obj1 )

{

pet pet1 = (pet)obj1 ;

return ( pet1.name.equals( name ) ) ;

}

}

public class equals2

{

public static void main(String args[] )

{

pet object1 = new pet() ; object1.name = "Ginger" ;

pet object2 = new pet() ; object2.name = "Ginger" ;

if ( object1 == object2 )

System.out.println( "Equals with the == sign" ) ;

if ( object1.equals(object2) )

System.out.println( "Equals with the equals method." ) ;

}

}

Output:

[amittal@hills Operators]$ java equals2

Equals with the equals method.

We have overridden the method "equals" in the pet class.

public boolean equals( Object obj1 )

{

pet pet1 = (pet)obj1 ;

return ( pet1.name.equals( name ) ) ;

}

We are doing comparisons by name and we get the expected result.

Increment Operators

We have 2 increment operators postfix and prefix. Both of them increment a value by 1 . The difference is when they do it.

Exercises

1)

What does the below print ?

public class ex1

{

public static void main(String[] args) {

Integer n1 = new Integer(47);

Integer n2 = new Integer(47);

System.out.println(n1 == n2);

System.out.println(n1 != n2);

}

}

Solutions

1)

/* Output:

false

true