Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Quicky String Question

 
Sue Hunt
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there.
Quick one I hope.
I'm trying to do a while loop, testing that a string is NOT equal to the user's input. I know how to do equals, but how would I do it for a not equal too.
As usually, I'm probably missing something right under my nose.
Cheers
Sue
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
!string1.equals(string2)
 
Sue Hunt
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul
so I could do this then...
!mainQuery.equals("q");
Cheers
Sue
 
fred rosenberger
lowercase baba
Bartender
Posts: 12202
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the "!" operator (i think its an operator, but in any case) simply flips ANY boolean value to the opposite value. ANYWHERE you have something that evaluates to TRUE or FALSE, you can stick the ! in front of it.
i assume mainQuery.equals("q") returns a boolean (if not, we have major naming issues ). therefore, yes, you can put your ! in front of it.
 
s choukse
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may like to consider this.
mainQuery.equals("q") will result in a NullPointerException if value of object "mainQuery" is null. It is always a good practice to compare in the following way
"sting literal".equals(sting_instance);
in you case
"q".equals(mainQuery)
- Saurabh
 
sever oon
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or, along the same lines as the last post, become familiar with the so-called "short-circuit" operators in Java, || and &&. These are called short-circuit operators because you can short-circuit the remainder of a logical operation using them. Example:

You might expect the above to print out: "foo! bar!". But it doesn't. It'll never evaluate the foo() method because x is false, so it doesn't need to continue evaluating the rest of the logical AND statement.
This is useful mainly for null checks, though I suppose you could think of a thousand more bizarre uses:

sev
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic