You've now called a number of methods, like Math.max(2.0, 3.0);, but how would
you define such a method?
(This method returns the larger of the two numbers you pass in, by the way. In this example, it would return 3.0.)
A little bit like this:
public class Math {
public static double max(double a, double b) {
if (a > b) {
return a;
}
return b;
}
}Let's break this down.
The method's signature is the following:
public static double max(double a, double b)
The signature says what the method takes, and what the method returns, along with other information that we'll cover later.
public: This means that the method can be called outside of theMathclass. We'll cover this more in chapter 6.static: We'll cover this more in chapter 6.double: This method returns adouble. This can be any data type (int,String, etc.) orvoid, which means that the method returns nothing.max(double a, double b): The method is called max, and takes two parameters:a, which is adouble, andbwhich is also adouble.
There's another new piece of syntax here: the return keyword. The idea is that
when you return, the method immediately exits at that point. If the return
type of your method is void, you can just do return;. If the return type is
not void, you must return something of the appropriate data type. E.g. if
your return type is double, this will work: return 3.1;, but this will not:
return "foo";.
Here are your PracticeIt problems: