How to do! = For strings

I am doing a program in java and all this is fine until I want to make a while loop like this:

while(String.notEqual(Something)){...}

I know there are none like notEqual, but is there something similar?

+6
source share
8 answers

Use! syntax. eg,

 if (!"ABC".equals("XYZ")) { // do something } 
+18
source

use .equals in combination with the operator ! . from JLS ยง15.15.6 ,

The expression type of the operand of a unary operator ! must be boolean or boolean , or a compile-time error occurs.

The type of the unary expression of the logical complement boolean .

At run time, the operand is decompressed (see 5.1.8), if necessary. The value of the unary logical complement expression is true if the value of the (possibly transformed) operand is false and false if the (possibly transformed) value of the operand is true .

+3
source
 String a = "hello"; String b = "nothello"; while(!a.equals(b)){...} 
+2
source
 String text1 = new String("foo"); String text2 = new String("foo"); while(text1.equals(text2)==false)//Comparing with logical no { //Other stuff... } while(!text1.equals(text2))//Negate the original statement { //Other stuff... } 
+1
source

If you want case-sensitive comparison to use equals() , otherwise you can use equalsIgnoreCase() .

 String s1 = "a"; String s2 = "A"; s1.equals(s2); // false if(!s1.equals(s2)){ // do something } s1.equalsIgnoreCase(s2); // true 

Another way to compare strings, which is useful for some cases (e.g. sorting), is to use compareTo , which returns 0 if the strings are equal, > 0 if s1> s2 and < 0 otherwise

 if(s1.compareTo(s2) != 0){ // not equal } 

There is also compareToIgnoreCase

+1
source
 while(!string.equals(Something)) { // Do some stuffs } 
0
source

There is no such thing called notEquals, so if you want to use negation!

 while(!"something".equals(yourString){ //do something } 
0
source

if you changed the line in your loop, it is better to consider the NULL condition.

 while(something != null && !"constString".equals(something)){ //todo... } 
0
source

All Articles