Java – A line of java code and what it does

equalsjavasetterstring

So I have purchased the book "Java for Dummies" 4th Edition, and I must say it is probably the best 30 dollars I have ever spent on a book. I'm not new to coding, am actually fairly decent at at it if I say so myself.

However, I've come across a line of code that has me a touch confused:

public void setName(String n)
{
     if(!n.equals(""))
     {
          name = n;
     }
}

My question comes up on the third line, the if(!n.equals("")) part…I know how if loops work (ie: if(this == that){do stuff}), but I've not seen the !n.equals("") set up before. Can anyone please explain it to me?

PS: Just to throw in a guess. Is it the same as:

public void setName(String n)
{
     if(n != "")
     {
          name = n
     }
}

I think it's just a way to make sure that if the user doesn't type in a name (ie. myAccount.setName = ""; ) it doesn't kick back an error and runs like normal, but I wasn't sure.

Thanks in advance for the help!

EDIT: changed my "myAccount.name = "";" to "myAccount.setName = "";", sorry about the confusion.

THANK YOU: Goes to Asaph, appreciate the answer! Same to Lucas Aardvark, he answered as well, but Asaph answered my verification comment in his own answer first, thanks to everyone!

Best Solution

In java, strings are immutable but not interned, so if(""==n) might or might not be true for another string for which "".equals(n) is true.

Just to confuse you more, this is bad code, it will get a NullPointerException if called with null as the argument. It should be written as "".equals(n)