Groovy: часть 5 – операторы

groovy-logoПредыдущая часть – Groovy: часть 4 – переменные.

Оператор – специальный символ, который указывает компилятору на выполнение математических или логиеских операций.

В Groovy имеются следующие типы операторов:

  • арифметические
  • операторы сравнения
  • логические
  • побитовые операторы
  • операторы присваивания

Арифметические операторы

В Groovy, как и в любом другом языке программирвоания, имеются арифметические операторы:

Operator Description Example
+ Addition of two operands 1 + 2 will give 3
Subtracts second operand from the first 2 − 1 will give 1
* Multiplication of both operands 2 * 2 will give 4
/ Division of numerator by denominator 3 / 2 will give 1.5
% Modulus Operator and remainder of after an integer/float division 3 % 2 will give 1
++ Incremental operators used to increment the value of an operand by 1 int x = 5;

x++;

x will give 6

Incremental operators used to decrement the value of an operand by 1 int x = 5;

x–;

x will give 4

Операторы сравнения

Операторы сравнения позволяют выполнять сравнение объектов:

Operator Description Example
== Tests the equality between two objects 2 == 2 will give true
!= Tests the difference between two objects 3 != 2 will give true
< Checks to see if the left objects is less than the right operand. 2 < 3 will give true
<= Checks to see if the left objects is less than or equal to the right operand. 2 <= 3 will give true
> Checks to see if the left objects is greater than the right operand. 3 > 2 will give true
>= Checks to see if the left objects is greater than or equal to the right operand. 3 >= 2 will give true

Логические операторы

Логические операторы используются для вычисления булиевых (True/False) значений:

Operator Description Example
&& This is the logical “and” operator true && true will give true
|| This is the logical “or” operator true || true will give true
! This is the logical “not” operator !false will give true

Побитовые операторы

Groovy предоставляет четыре побитовых оператора:

Operator Description
& This is the bitwise “and” operator
| This is the bitwise “or” operator
^ This is the bitwise “xor” or Exclusive or operator
~ This is the bitwise negation operator

Операторы присваивания

Groovy так же позволяет использование операторов присваивания:

Operator Description Example
+= This adds right operand to the left operand and assigns the result to left operand. def A = 5

A+=3

Output will be 8

-= This subtracts right operand from the left operand and assigns the result to left operand def A = 5

A-=3

Output will be 2

*= This multiplies right operand with the left operand and assigns the result to left operand def A = 5

A*=3

Output will be 15

/= This divides left operand with the right operand and assigns the result to left operand def A = 6

A/=3

Output will be 2

%= This takes modulus using two operands and assigns the result to left operand def A = 5

A%=3

Output will be 2

Операторы диапазона

Среди прочего – Groovy поддерживает концепцию диапазонов и предоставляет объявление операторов диапазона с помощью оператора “..".

Простой пример использования такого оператора выглядит так:

groovy:000> def range = 0..5 
===> [0, 1, 2, 3, 4, 5]

Тут определяется простой диапазон чисел, которые хранятся в переменной с именем range, который начинается с нуля и заканчивается 5.

Пример использования:

class Example { 
   static void main(String[] args) { 
      def range = 5..10; 
      println(range); 
      println(range.get(2)); 
   } 
}

Результат:

$ ./example.groovy 
[5, 6, 7, 8, 9, 10]
7

Приоритеты операторов

Ниже предоставлен список приоритетов операторов в Groovy, от наивысшего – к самому низкому:

Operators Names
++ — + – pre increment/decrement, unary plus, unary minus
* / % multiply, div, modulo
+ – addition, subtraction
== != <=> equals, not equals, compare to
& binary/bitwise and
^ binary/bitwise xor
| binary/bitwise or
&& logical and
|| logical or
= **= *= /= %= += -= <<= >>= >>>= &= ^= |= Various assignment operators

Продолжение – часть 6 – циклы.