Not all equals you expect will be equal.

In Java you must understand how equality is tested, carefully choosing between (a == b) and a.equals(b).

For basic types (int, long, char) the equals operator (==) performs a direct comparison of the two values; e.g. does 5 equal 5?    However, for object references (including Integer, Long, Character, String), the equals operator compares only if the two objects share the same “address” in memory*.  The == equals operator always returns false when the two objects are independent, even when they have identical content.

Use the .equals( ) function instead for objects, unless you are checking that a reference is null or not-null.

An example is below.

// Wrong Comparison
if (userName == "Fred")   
{
    ....
}

The above code compares the memory address the userName variable is stored with against the memory address of the constant text “Fred”.  Unless a previous line assigned “Fred” to userName, this will never be a true condition.  What the programmer meant to write is below. Note we reversed the arguments to avoid failing when username is null.

if ("Fred".equals(username))
{
    ....
}

Another common mistake is using the .equals() method to check for null, which never works.

In the following example, if a project is ever equal to null, a  NullPointerException will result because functions cannot be called on a null pointer.

// Silly use of .equals
if (project.equals(null) || project.equals("null"))    
{
    ....
}

The correct way to test if project is null is using the == operator, as follows.


if (project == null)
{
    ....
}

The == operator can't be used to compare the values of two Strings.  While the code will compile, it compares memory address, not contents of the memory addresses.

private boolean processFile(File fileToProcess, String type)
{
    // cannot compare two String values using '=='
    if (type == DataFile.TYPE_AVI)
    :

A correct way to test two strings for equality is to use the .equals() method, but be sure to check for null first.

private boolean processFile(File fileToProcess, String type)
{
    if (type != null && type.equals(DataFile.TYPE_AVI))
    :

A more concise method of the above avoids a check for null:

private boolean processFile(File fileToProcess, String type)
{
    if (DataFile.TYPE_AVI.equals(type))
    :

*Java doesn't strictly use memory addresses like in C++ but it will do for illustrating the example.

blog comments powered by Disqus