OneCompiler

Methods

Method is a sub-routine which contains set of statements which increases re-usuability and modularity.

How to define a Method

def methodName(parameters) { 
   //Method code 
}

Examples

// simple example to show a method without parameters
greetings();

def greetings()
{
  println("Hello World!!")
}

Check result here

// Example for method with parameters
sum(10,20)

def sum( int x, int y){
  def result = x + y;
  println "Sum of $x and $y is $result"
}

Check result here

You can also default parameters to some values.

greetings("foo");
greetings();
def greetings(String name = "NA")
{
  println("Hello $name!!")
}

Check result here