The concept of the method. General form. Method parameters Return from method. Operator return. Return an object from a method. Examples of methods

The concept of the method. General form. Method parameters. Returning from method. Operator return. Return an object from a method. Examples of methods


Contents



1. The concept of the method. Method definition in class

As you know, classes can contain data and methods. In Java, data is also called instance variables or objects. Methods are also called subroutines or functions. Method is a subroutine designated by name. With this name, you can call the subroutine code (method code). Calling a method by name can be made from another method many times depending on the task being performed. Each time you call a method name, the method code is executed instead of that name. Methods in a class are named program code that defines some work on class data. A class can contain any number of methods. In addition, a class can be implemented without methods. Most often, class methods process data (instance variables) of a class.

2. Parameters of methods. Returning values from methods

Methods can accept parameters. By the number of received parameters of the methods are divided into:

  • methods that receive parameters (methods with parameters or parameterized methods). In this case, the list of parameters is indicated in brackets after the name of the method;
  • methods without parameters. In this case, empty parentheses ( ) are indicated after the method name.

More details about the parameters of the methods are described in the following topic:

The method can return a value. Before the name of the method indicates the type of value that the method returns. In terms of returning values from a method, methods can be of two types:

  • methods that return value. In this case, the method must contain a return statement with a return code;
  • methods that do not return values. Before the name of a method that does not return a value, the void keyword is specified. In this case, the method need not contain the return statement. If such a method contains a return statement, then nothing is indicated after this statement.

3. The general form for declaring a method that returns a value

The method can return a value. Such a method can be used in expressions. So, in the Pascal programming language, the methods that return a value are called function. The general form of the method declaration, which returns a value and takes parameters, is as follows:

return_type MethodName(type1 param1, type2 param2, ..., typeN paramN) {
    // method body - program code
    // ...
}

where

  • MethodName – method name;
  • return_type – the type returned by the method. This may be a primitive (simple) type, or a type (class) declared additionally in the program;
  • param1, param2, paramN – parameter names that have type1, type2, typeN types respectively. The number of parameters in the methods can be arbitrary. In addition, the parameters can be omitted. If the method contains no parameters, then empty brackets ( ) are specified instead of the parameter list.

If the method returns a value and does not receive any parameters, then the general form of such a method is as follows:

return_type MethodName() {
    // method body
    // ...
}

4. Methods that do not return a value. General form. The void keyword

If the method does not return a value, then the keyword void is specified before its declaration. Such a method cannot be used in expressions. So, in the programming language Pascal, methods that do not return a value are called procedures.

The general form of a method declaration that does not return a value but takes parameters is:

void MethodName(type1 param1, type2 param2, ..., type param) {
    // method body - program code
    // ...
}

where

  • void – reserved keyword (specifier) indicating that the method returns no value;
  • MethodName – method name;
  • param1, param2, paramN – parameter names that are of type1, type2, typeN type respectively.

If the method does not return a value, and does not receive parameters, the general form of this method is as follows:

void MethodName() {
    // method body
    // ...
}

5. Examples of methods that do not receive parameters and do not return values 

Example 1. A method without parameters with the name MethodWithoutParameters() is declared. The void keyword indicates that the method does not return any value. 

// method that accepts no parameters and does not return values
void MethodWithoutParameters() {
    return;
}

This method can be written differently

// the return statement is optional
void MethodWithoutParameters() {

}

Example 2. The implementation of the ShowInfo() method is demonstrated in the DemoMethods class, which displays information about a Web resource.

class DemoMethods {
    // method that displays general information about our web resource
    void ShowInfo() {
        System.out.println("Website Information:");
        System.out.println("Main page: https://www.bestprog.net");
        System.out.println("Programming: theory and practice");
        System.out.println("The website was created on December 08, 2015");
    }
}

Using the ShowInfo() method of the DemoMethods class in another code can be the following:

// the use of ShowInfo() method of the DemoMethods class
DemoMethods dm = new DemoMethods();    // create an instance of the class
dm.ShowInfo(); // invoke the method

As a result of the method call, the following result will be displayed in the console:

Website Information:
Main page: https://www.bestprog.net
Programming: theory and practice
The website was created on December 08, 2015

6. Examples of methods that do not receive parameters and return a value

Example 1. In the MathConstants class, the Pi() method is declared, which returns the value of the number π. The Pi() method returns a double value using the return operator.

// a class that contains a method without parameters, which returns a value
class MathConstants {
    // method that returns pi
    double Pi() {
        return 3.1415926535;
    }
}

The following demonstrates how to use the Pi() method to calculate the area of a circle:

// the use of Pi() method of the MathConstants class
MathConstants mc = new MathConstants();
double area, radius;
radius = 2; // calculate the area of a circle of radius 2
area = mc.Pi() * radius * radius; // area = 12.566370614

Example 2. The class Circle is declared, containing internal data (x, y, radius) and methods Area(), LenOrigin() which perform calculations on this data.

// a class that implements the circle
class Circle {
    double x, y; // coordinates of the center of the circle
    double radius; // radius of circle

    // method that returns the area of a circle of given radius
    double Area() {
        final double pi = 3.141592f; // pi constant
        return pi * radius * radius;
    }

    // method that returns the distance from the center of the circle (x, y) to the origin (0; 0)
    double LenOrigin() {
        double len = Math.sqrt(x*x + y*y);
        return len;
    }
}

The use of the Circle class can be as follows

// the use of methods of the class Circle
Circle cr = new Circle();
double area, length;

// fill class instance with values
cr.x = 2.5;
cr.y = 4.2;
cr.radius = 3;

// invoking of methods
area = cr.Area(); // area of a circle, area = 28.274328231811523
length = cr.LenOrigin(); // length = 4.887739763939975

7. Examples of methods that take parameters and do not return values

Example 1. The example declares the class Month, which implements the month of the year. The class implements the SetMonth() method, which receives the month number as an input parameter. The SetMonth() method does not return a value. Depending on the month number, the method sets the following internal variables:

  • number of month (month field);
  • the number of days in the month (days field);
  • name of the month (the name field).

The declaration of the class Month is as follows:

// class that implements the month of the year
class Month {
    int month; // month number in year 1..12
    int days; // maximum number of days in a month
    String name; // month name

    // a method that sets a new month by its number
    void SetMonth(int _month) {
        // checking if the data is correct
        if ((_month<1)||(_month>12))
            return;

        // month number
        month = _month;

        // maximum number of days in a month
        switch (_month) {
            case 2:
                days = 29;
            break;
            case 4: case 6: case 9: case 11:
                days = 30;
            break;
            default:
                days = 31;
        }

        // month name
        switch (_month) {
            case 1: name = "Jan"; break;
            case 2: name = "Feb"; break;
            case 3: name = "Mar"; break;
            case 4: name = "Apr"; break;
            case 5: name = "May"; break;
            case 6: name = "Jun"; break;
            case 7: name = "Jul"; break;
            case 8: name = "Aug"; break;
            case 9: name = "Sep"; break;
            case 10: name = "Oct"; break;
            case 11: name = "Nov"; break;
            case 12: name = "Dec"; break;
            default: name = "";
        }
    }
}

The use of method is as follows:

// demonstration of a method that takes parameters and does not return values
Month mn = new Month(); // create an instance of the class
mn.SetMonth(5); // set data for month "May"

// checking
int days;
String name;
days = mn.days; // days = 31
name = mn.name; // name = "May"

Example 2. The Circle class declares an overloaded SetData() method that sets the value of the internal variables of an instance. The method does not return a value — the keyword void is specified before the method name. The SetData() method has two implementations:

  • the implementation SetData(double, double, double). The method gets 3 double parameters that set the values of the corresponding internal class variables;
  • the implementation SetData(Circle). In this case, the method receives an instance of the same class as the data source.
// a class that implements the circle
class Circle {
    double x, y; // coordinates of the center of the circle
    double radius; // radius of circle

    // method that accepts 3 double parameters
    // method does not return value (void)
    void SetData(double x, double y, double radius) {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    // method that gets an instance of type Circle
    // method does not return value
    void SetData(Circle cr) {
        x = cr.x;
        y = cr.y;
        radius = cr.radius;
    }
}

8. Examples of methods that accept parameters and return a value

Example 1. Develop the class methods that solve the following task. According to the numbers a, b, calculate:

u = f(0.5, a) + f(2·a+2·b, a-2·b)

if

f(x, y) = x2 + x·y - y2

To solve this problem, a class called Solution is declared. A two methods are implemented in the class:

  • a method called f() that accepts two parameters of type double. This method implements the f() function.
  • a method named u() without parameters, which invokes the f() function to return the result.

The implementation of the Solution class is as follows.

// the solution of the task
class Solution {
    // method that implements the function f(x, y)
    double f(double x, double y) {
        return x*x+x*y-y*y;
    }

    // method that implements the function u(a,b)
    double u(double a, double b) {
        return f(0.5, a) + f(2*a+2*b, a-2*b);
    }
}

Using the Solution class in some method

// using of methods of the Solution class
Solution sl = new Solution();
double res;
res = sl.u(3,7); // res = 51.75

Example 2. The Line class is declared, which implements methods for working with the segment specified by the coordinates (x1, y1), (x2, y2). The class implements two methods IsLine() and Length(). Each method accepts 4 parameters and returns a value.

The class implementation is as follows

// class containing methods for working with segment,
// which is given by the coordinates of its points (x1, y1) and (x2, y2)
class Line {
    // a method that determines whether the coordinates of the points (x1, y1) and (x2, y2) form a segment
    boolean IsLine(double x1, double y1, double x2, double y2) {
        if ((x1==x2)&&(y1==y2)) return false;
        return true;
    }

    // a method that determines the length of a segment by its coordinates
    double Length(double x1, double y1, double x2, double y2) {
        double len;
        len = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
        return len;
    }
}

Below is a code snippet that demonstrates the use of the Line class methods.

// the use of methods of Line class
Line ln = new Line();
double x1, y1, x2, y2;
double len = 0;

// data input
x1 = 3.5; y1 = 2.8;
x2 = 7.2; y2 = 7.8;

// calculation
if (ln.IsLine(x1, y1, x2, y2))
len = ln.Length(x1, y1, x2, y2); // Length = 6.220128616033595

9. Can the method body be empty?

The body of a method can be empty, that is, it does not contain a single operator. Methods without operators can be used as stub methods, which currently do not contain code, but in which the necessary code can later be entered.

10. How is the method name used in expressions? Example

Method name can be used in expressions. For the method name to be used in expressions, this method must return a value using the return statement. The return type from the method will be the type of the method name that is used in the expression. You cannot use a method in the expression that returns the void type.

Example. Let a method named p() be defined that calculates the following expression p(x) = 3x³+2x²+x. The implementation of the method is as follows

// method that calculates the value of expression
// based on an input value x
static double p(double x) {
    return 3*x*x*x+2*x*x+x;
}

Then, the method name p() can be used for calculations in different expressions. For example

// use of method name in expression
double res;
double a, b, c, d;

a = 2.5;
b = 3.2;
c = -1.8;
d = 14.2;

// The p() method name is used in the expression.
res = (p(a) + p(b) + p(c) + p(d)) / 4; // res = 43107.70404999999

In the above code, the p() method name is used to calculate the expression:

y = (p(a) + p(b) + p(c) + p(d))/4

where a, b, c, d – some input values.

11. What is the purpose of the operator return? The general form of the operator return. Return from method. Examples

The return statement is used to return a value from a method. The return statement can have two forms of using. In the first case, the general form of the return statement is:

return expression;

where expression – some expression, variable or constant. This form is used when the method returns a value. The name of such a method can be used in expressions, if the type of expression supports such using. The second form of the return statement is as follows:

return;

In this case, the return statement is specified in a method that returns no value. Such method returns the void type.

Example 1. The use of return statement in a method that returns a double result is demonstrated.

// method that determines the maximum value between three numbers
static double Max(double a, double b, double c) {
    double max = a;
    if (max<b) max=b;
    if (max<c) max=c;
    return max; // return operator returns double type
}

Example 2. The return of a reference to the class object from the method using the operator return is demonstrated. Let class A be given

// some class
class A {
    int a;
}

Below is a method that creates an object of class A. The memory for object and a reference to this object using the operator return is allocated.

// method that creates an object of class A
static A CreateObj() {
    A obj = new A(); // create an object (instance) of class A
    obj.a = 5;
    return obj; // return a class A object from a method
}

The use of the CreateObj() method can be as follows

// the use of method in another code
A obj;
obj = CreateObjA(); // obj.a = 5

Example 3. The use of a return statement from a method that returns no value is demonstrated

// method that returns nothing
void NoReturn() {
    return;
}

12. What programming errors can occur if the return statement is used incorrectly?

If the method returns a value of some type other than void, then the following rules apply:

  • the body of the method must have a return statement that returns a value. If the return statement is missing in some branch of the method execution, the compiler will generate an error message;
  • in the body of a method that returns a value (except for void), any branch must be terminated by a return statement. Otherwise, the compiler will generate an error message;
  • the code of the method must be constructed in such a way that when executing a certain branch of the method, the return statement follows the last. If after return you specify any other program code, the compiler will generate the error “Unreachable code”.

13. Is it necessary to use the return statement if the method does not return a value?

No, it isn’t.


Related topics