Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A line of java code and what it does?

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!

like image 300
Soully Avatar asked Oct 01 '09 03:10

Soully


2 Answers

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)

like image 184
ddyer Avatar answered Nov 09 '22 12:11

ddyer


if(!n.equals(""))
{
     name = n;
}

means if n is not an empty String, assign its value to name.

In Java, every Object has an equals(Object o) method to test for equality with another Object. The == operator is typically used to compare primitives. It can also be used to compare Objects for "sameness". ie. the two Objects are in fact the same instance. This comes in handy for immutable types such as Strings and all the Object wrappers for the primitive types such as Integer and Long.

like image 24
Asaph Avatar answered Nov 09 '22 14:11

Asaph