A line of java code and what it does?
equals, java, setter, string
Solution
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.
Problem
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!