關(guān)系運算符允許對象的比較。以下是Groovy中可用的關(guān)系運算符 -
運算符 | 描述 | 例子 |
== | 測試兩個對象之間的等同性 | 2 == 2將得到true |
!= | 測試兩個對象之間的差異 | 3!= 2將得到true |
< | 檢查左對象是否小于正確的操作數(shù)。 | 2 < 3將得到true |
<= | 檢查左對象是否小于或等于右操作數(shù)。 | 2 < 3將得到true |
> | 檢查左對象是否大于右操作數(shù)。 | 3 > 2將得到true |
>= | 檢查左對象是否大于或等于右操作數(shù)。 | 3 = 2將得到true |
以下代碼段顯示了如何使用各種運算符。
class Example { static void main(String[] args) { def x = 5; def y = 10; def z = 8; if(x == y) { println("x is equal to y"); } else println("x is not equal to y"); if(z != y) { println("z is not equal to y"); } else println("z is equal to y"); if(z != y) { println("z is not equal to y"); } else println("z is equal to y"); if(z<y) { println("z is less than y"); } else println("z is greater than y"); if(x<=y) { println("x is less than y"); } else println("x is greater than y"); if(x>y) { println("x is greater than y"); } else println("x is less than y"); if(x>=y) { println("x is greater or equal to y"); } else println("x is less than y"); } }
當(dāng)我們運行上面的程序,我們將得到以下結(jié)果。可以看出,結(jié)果如從上面所示的操作符的描述所預(yù)期的。
x is not equal to y z is not equal to y z is not equal to y z is less than y x is less than y x is less than y x is less than y
更多建議: