if-else
Sometimes we want to control the flow of the code we make.
So that a block of code executes when certain conditions are met or execute another block of code and ignore other statements.
In order to achieve this we utilize something called if-else
.
This is the most basic flow control statements in groovy and actually in any most of the programming languages.
if-else
tell your script to execute certain parts of the code only if a particular condition evaluates to true or false.
General Form of if –else
- if(condition){
- //block of code to execute if the condition is met
- }else{
- //block of code to execute if the condition in if is not met
- }
- if(condition)
- //1 line of code to execute
- else
- //1 line of code to execute
- def var_A = 100
- if(var_A == 100)
- setAttribute(‘FieldName’,var_A)
- else
- setAttribute(‘FieldName’,200)
- def var_A = 100
- if(var_A == 100){
- setAttribute(‘FieldName’,var_A)
- }
- else{
- setAttribute(‘FieldName’,200)
- }
- def var_A = 100
- def var_B = 200
- if(var_A <150){
- var_A = var_B + 400
- setAttribute(‘FieldName’,var_A)
- }else{
- var_B ++
- var_A = var_B + 600
- setAttribute(‘FieldName’,var_B)
- }
- if(var_A <150)
- var_A = var_B + 400
- setAttribute(‘FieldName’,var_A)
- else
- var_B ++
- var_A = var_B + 600
- setAttribute(‘FieldName’,var_B)
- if(var_A <150){
- var_A = var_B + 400
- setAttribute(‘FieldName’,var_A)
- }else
- setAttribute(‘FieldName’,800)
- If(condition){
- //block of code to execute if the if condition is met
- }else if(condition){
- //block of code to execute if the else if condition is met
- }else{
- //block of code to execute if none of the conditions above are met
- }
- def var_A = 100
- if(var_A < 100){
- setAttribute(‘FieldName’,10)
- }
- else if (var_A > 100){
- setAttribute(‘FieldName’,300)
- }else {
- setAttribute(‘FieldName’,100)
- }
- if(condition)
- //1 line of code
- else if(condition)
- //1 line of code
- else if(condition)
- //1 line of code
- else
- //1 line of code
- if(condition){
- // some code
- }
- if(condition){
- //code of block
- }else{
- return false //this line means nothing will be returned, so basically nothing happens
- }
- switch(Variable_to_Check){
- case 1:
- //code to execute
- break;
- case 2:
- //code to execute
- break;
- case 3:
- //code to execute
- break;
- default
- //code to execute
- break;
- }
- def var_number = 10
- switch(var_number ){
- case 1:
- println(“var_number = “ + 1)
- break;
- case 5:
- println(“var_number = “ + 5)
- break;
- case 10:
- println(“var_number = “ + 10)
- break;
- case 100:
- println(“var_number = “ + 100)
- break;
- default:
- println(“var_number has a different value”
- break;
- }