Knowledge Base Article

Groovy Decision Logic

Introduction

Groovy is based on Java, and many of the same decision logic constructs in Java work in Groovy.  The following groups of Groovy code show the appropriate syntax for basic decision logic in Groovy.

Groovy Code Examples

assert x != 0 :"X must not be zero"  //assert: if true, continue. False, stop and show message.

for (int i = 0; i < 5; i++) {    // Example of FOR loop syntax
      x = x+1
      }  
  while ( y-- > 0 ) {         
 // Example of WHILE loop syntax
       x++
       }
    if ( x > y ) {                        
// Example of IF then ELSE syntax
       x = 10
       } else {
       x = y + 10
       }

x = y % 10                           // Example of modulus:  the remainder of y divided by 10

x = (x > y) ? 10 : y +10         //Example of Conditional assignment syntax

switch ( pix ) {                     //Example of CASE statement (switch) syntax
       case "foo":
           y = x                              
// lets fall through
       case "bar":
           y += x
           break
        default:
            return "foo-bar error"
        }
                                        // end switch

def xyp = "$x, $y, $pix"        // Example of creating a string with the values of parameters

return xyp                               // Example of RETURN statement.