Defining MethodsLearn how to declare/define methods in Java The method definition follows the pattern MODIFIERS RETURN_TYPE METHOD_NAME (PARAMETERS) EXCEPTIONS_THROWN { //More code here } Let us have look at the below example.
The method name and the parameters are together called Method Signature. The below method accepts 2 parameters. Multiple parameters are separated by comma.
public double getDiscount(double labelPrice, boolean isSeniorCitizen) throws Exception {
if (labelPrice < 0.0) {
throw new Exception("Price Cannot Be A Negative Amount");
}
//20% discount for senior citizen
if (isSeniorCitizen) {
return 0.8 * labelPrice;
}
//Discount is 10%
return 0.9 * labelPrice;
}
Note: We will explain more about Exception in later chapters.
|