2013年10月21日 星期一

java-not-equal





In Java, like most C based programming languages,

"not equal" is "!=".

This operation is only limited to primitive variables like characters, integers (and variants), and booleans. For strings, "not equal" symbol"!=" is not used. If you do perform not equal operation for string variables, you can try this trick.

"if ( ! (string1.equals(string2)) ) {....}"

or if you don't care about letter cases, use this..

"if ( ! (string1.equalsIgnoreCase(string2)) ) {....}"

Same is true for other objects in Java. Using operation "!=" between two objects in Java will not give you a compilation error but rather would give you a logical error at runtime since it will not compare the values of the objects but rather compares their logical memory addresses.

沒有留言:

張貼留言