cubbuk
cubbuk

Reputation: 7920

Strange issue in equals comparison

I am having a strange issue with the followin syntax:

The following code block doesn't throw null pointer exception

Map<String, String> requestHeaderMap = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap();

if(!"partial/ajax".equals(requestHeaderMap.get("faces-request")))    
{
    System.out.println("This works");
}

But this one throws null pointer exception:

FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("faces-request").equals("partial/ajax")

I just couldn't figure out whats wrong here. I don't see any difference between two call except for readability.

Upvotes: 2

Views: 164

Answers (4)

mstrewe
mstrewe

Reputation: 416

if(!"partial/ajax".equals(requestHeaderMap.get("faces-request")))  

is true because this means

if( !("partial/ajax".equals(null)).



If you try

null.equals("partial/ajax")

this will raise the the exception.

Upvotes: 1

sharakan
sharakan

Reputation: 6901

FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("faces-request") is null. Your version that works does so because you have the equals reversed, the two operations boil down to:

null.equals(object)

or

object.equals(null)

the first throws a NullPointerException, the second evaulates to false.

Upvotes: 6

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

It's because getRequestHeaderMap().get("faces-request") can return null and null.equals("partial/ajax") throws an exceoption.

However, "partial/ajax".equals(...) will never throw an exception, even if it is being compared with null.

That, in my personal opnion, is the only good thing about this Joda construct.

Upvotes: 0

Ryan Stewart
Ryan Stewart

Reputation: 128829

The two do things in different orders. It's like the difference between x.equals(y) and y.equals(x). If y is null, only the second one of those will throw an NPE. In your case, requestHeaderMap.get("faces-request") is null.

This doesn't throw the exception because *.equals(null) is perfectly fine:

"partial/ajax".equals(requestHeaderMap.get("faces-request")

On the other hand, this is trying to dereference null:

getRequestHeaderMap().get("faces-request").equals("partial/ajax")

Upvotes: 2

Related Questions