Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of Java .equals() method?

I'm trying to write a little block of code in Java with a do-while loop that asks the user's name. If it isn't the name the code is looking for, then it just repeats itself. For example,

Scanner scan = new Scanner();
do { 
   System.out.println("whats your name?"); 
   String name = scan.nextLine(); 
} while ("jack".equals(name));  ////// <<<<

It's where I marked with <<<< that I don't know what to do. I need something like !=, but that does not work with strings.

So what can I put here?

like image 695
user2465514 Avatar asked Nov 30 '22 03:11

user2465514


2 Answers

The exclamation point ! represents negation or compliment. while(!"jack".equals(name)){ }

like image 138
Mike Nitchie Avatar answered Dec 13 '22 03:12

Mike Nitchie


The boolean not ! operator is the cleanest way. Of course you could also say

if ("jack".equals(name) == false) { ... }

or you could say

if ("jack".equals(name) != true) { ... }

Beware if calling .equals() on an object that could be null or you'll get a NullPointerException. In that case, something like...

if !((myVar == yourVar) || ((yourVar != null) && yourVar.equals(myVar))) { ... } 

... would guard against an NullPointerException and be true if they're no equal, including them both not being null. Quite a brain-twister huh? I think that logic is sound, if ugly. That's why I write a StringUtil class containing this logic in many projects!

That's why it's a better convention to invoke the .equals() method on the string literal rather than the String you're testing.

like image 36
Alex Worden Avatar answered Dec 13 '22 01:12

Alex Worden