Functions to methods

Javascript functions

In Javascript you write a function like:

function hypotenuse(a, b) {
  return Math.sqrt(a ** 2 + b ** 2);
}
  • function tells us it’s a function

  • hypotenuse is the name.

  • a and b are parameters.

  • And the body is enclosed in {}s.

Java methods

In Java we call it a method and write it like:

double hypotenuse(double a, double b) {
  return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
  • The first double is the return type

  • The parameters a and b also need types.

  • The body is basically the same but there’s no ** in Java.

Return types

Just like variables in Java need to be declared with their type a method needs to be declared with a return type that tells the compiler what kind of value the method returns.

This is how Java can statically check whether code like this is legal or not:

int x = someMethod();

For the compiler to know that’s okay I needs to know whether someMethod() returns an int or not.

Parameter types

Method parameters are just another kind of variable and all variables in Java have a declared type.

This lets Java statically check whether this is okay or not:

someOtherMethod(10, 20.0);

If the first parameter was declared to be an int and the second to be a double, everything is fine.