YouTip LogoYouTip

Java Methods

Java Methods

In the previous chapters, we often used System.out.println(). What is it?

  • println() is a method.
  • System is a system class.
  • out is the standard output object.

This statement calls the println() method of the standard output object out within the system class System.

So, what is a method?

A Java method is a collection of statements that are grouped together to perform a function.

  • Methods are an ordered combination of steps to solve a specific problem.
  • Methods are contained within classes or objects.
  • Methods are created in a program and called from other places.

Advantages of Methods

  • 1. Makes the program shorter and clearer.
  • 2. Facilitates program maintenance.
  • 3. Can improve the efficiency of program development.
  • 4. Enhances code reusability.

Method Naming Conventions

  • 1. The first word of a method name should start with a lowercase letter, and subsequent words should start with an uppercase letter, without using hyphens. For example: addPerson.
  • 2. Underscores may appear in JUnit test method names to separate logical components of the name. A typical pattern is: test<MethodUnderTest>_<state>, for example, testPop_emptyStack.

Defining a Method

Generally, defining a method includes the following syntax:

modifier returnType methodName(parameter list) {
    // method body
    return returnValue;
}

A method consists of a method header and a method body. Here are all the parts of a method:

  • Modifier: The modifier is optional and tells the compiler how to call the method. It defines the access type of the method.
  • Return Type: A method may return a value. returnValueType is the data type of the value returned by the method. Some methods perform the desired action but do not return a value. In this case, returnValueType is the keyword void.
  • Method Name: This is the actual name of the method. The method name and parameter list together form the method signature.
  • Parameter Type: Parameters are like placeholders. When a method is called, a value is passed to the parameter. This value is called an actual parameter or argument. The parameter list refers to the type, order, and number of parameters of the method. Parameters are optional; a method may contain no parameters.
  • Method Body: The method body contains specific statements that define the functionality of the method.

Image 1

For example:

public static int age(int birthday) {
    ...
}

Parameters can have multiple values:

static float interest(float principal, int year) {
    ...
}

Note: In some other languages, methods refer to procedures and functions. A method that returns a non-void return value is called a function; a method that returns a void return value is called a procedure.

Example

The following method contains two parameters, num1 and num2, and returns the maximum of these two parameters.

public static int max(int num1, int num2) {
    int result;
    if (num1 > num2)
        result = num1;
    else
        result = num2;
    return result;
}

A more concise version (using the ternary operator):

public static int max(int num1, int num2) {
    return num1 > num2 ? num1 : num2;
}

Calling a Method

Java supports two ways to call a method, depending on whether the method returns a value.

When a program calls a method, program control is transferred to the called method. The called method executes its return statement or reaches the closing brace of the method body, and then control is returned to the program.

When a method returns a value, the method call is usually treated as a value. For example:

int larger = max(30, 40);

If the method returns void, the method call must be a statement. For example, the method println returns void. The following call is a statement:

System.out.println("Welcome to Tutorial!");

Example

The following example demonstrates how to define a method and how to call it:

TestMax.java File Code:

public class TestMax {
    public static void main(String[] args) {
        int i = 5;
        int j = 2;
        int k = max(i, j);
        System.out.println(i + " and " + j + " compared, the maximum value is: " + k);
    }

    public static int max(int num1, int num2) {
        int result;
        if (num1 > num2)
            result = num1;
        else
            result = num2;
        return result;
    }
}

The compilation and execution result of the above example is as follows:

5 and 2 compared, the maximum value is: 5

This program contains a main method and a max method. The main method is called by the JVM. Apart from that, the main method is no different from other methods.

The header of the main method is fixed, as shown in the example, with the modifiers public and static, returning a void type value, the method name is main, and it also has a parameter of type String[]. String[] indicates that the parameter is a string array.


The void Keyword

This section explains how to declare and call a void method.

The following example declares a method named printGrade and calls it to print a given grade.

Example

TestVoidMethod.java File Code:

public class TestVoidMethod {
    public static void main(String[] args) {
        printGrade(78.5);
    }

    public static void printGrade(double score) {
        if (score >= 90.0) {
            System.out.println('A');
        } else if (score >= 80.0) {
            System.out.println('B');
        } else if (score >= 70.0) {
            System.out.println('C');
        } else if (score >= 60.0) {
            System.out.println('D');
        } else {
            System.out.println('F');
        }
    }
}

The compilation and execution result of the above example is as follows:

C

Here, the printGrade method is a void type method; it does not return a value.

A void method call must be a statement. Therefore, it is called as a statement on the third line of the main method, just like any statement ending with a semicolon.


Passing Parameters by Value

When calling a method, you need to provide parameters. You must provide them in the order specified by the parameter list.

For example, the following method prints a message n times consecutively:

TestVoidMethod.java File Code:

public static void nPrintln(String message, int n) {
    for (int i = 0; i < n; i++) {
        System.out.println(message);
    }
}

Example

The following example demonstrates the effect of pass-by-value.

This program creates a method used to swap two variables.

TestPassByValue.java File Code:

public class TestPassByValue {
    public static void main(String[] args) {
        int num1 = 1;
        int num2 = 2;
        System.out.println("Before swap, the value of num1 is: " + num1 + ", and the value of num2 is: " + num2);
        swap(num1, num2);
        System.out.println("After swap, the value of num1 is: " + num1 + ", and the value of num2 is: " + num2);
    }

    public static void swap(int n1, int n2) {
        System.out.println("t Entering the swap method");
        System.out.println("tt Before swap, the value of n1 is: " + n1 + ", and the value of n2 is: " + n2);
        int temp = n1;
        n1 = n2;
        n2 = temp;
        System.out.println("tt After swap, the value of n1 is: " + n1 + ", and the value of n2 is: " + n2);
    }
}

The compilation and execution result of the above example is as follows:

Before swap, the value of num1 is: 1, and the value of num2 is: 2
	 Entering the swap method
		 Before swap, the value of n1 is: 1, and the value of n2 is: 2
		 After swap, the value of n1 is: 2, and the value of n2 is: 1
After swap, the value of num1 is: 1, and the value of num2 is: 2

The swap method is called by passing two parameters. Interestingly, after the method is called, the values of the actual parameters have not changed.


Method Overloading

The max method used above is only suitable for int type data. But what if you want to get the maximum of two floating-point type data?

The solution is to create another method with the same name but different parameters, as shown in the following code:

public static double max(double num1, double num2) {
    if (num1 > num2)
        return num1;
    else
        return num2;
}

If you call the max method with an int parameter, the max method for int type will be called;

If you pass a double parameter, the max method for double type will be called. This is called method overloading;

That is, two methods in a class have the same name but different parameter lists.

The Java compiler determines which method should be called based on the method signature.

Method overloading makes the program clearer and easier to read. Methods that perform closely related tasks should use the same name.

Overloaded methods must have different parameter lists. You cannot overload a method based solely on different modifiers or return types.


Variable Scope

The scope of a variable is the part of the program where that variable can be referenced.

Variables defined within a method are called local variables.

The scope of a local variable starts from its declaration and ends when the block containing it ends.

Local variables must be declared before they can be used.

The scope of a method parameter covers the entire method. A parameter is actually a local variable.

Variables declared in the initialization part of a for loop have a scope that covers the entire loop.

However, variables declared within the loop body have a scope from their declaration to the end of the loop body. It includes the variable declaration shown below:

Image 2

You can declare a local variable with the same name multiple times in different non-nested blocks within a method, but you cannot declare a local variable twice within nested blocks.

Using Command-Line Arguments

Sometimes you want to pass messages to a program when running it. This is achieved by passing command-line arguments to the main() function.

Command-line arguments are information that follows the program name when executing the program.

Example

The following program prints all command-line arguments:

CommandLine.java File Code:

public class CommandLine {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println("args[" + i + "]: " + args);
        }
    }
}

Run the program as shown below:

$ javac CommandLine.java
$ java CommandLine this is a command line 200 -100
args: this
args: is
args: a
args: command
args: line
args: 200
args: -100

Constructors

A constructor is a special method used to create objects of a class. When an object is created using the new keyword, the constructor is automatically called to initialize the object's properties.

Constructor Characteristics:

  • Method name is the same as the class name: The constructor's name must be consistent with the class name.
  • No return type: Constructors have no return type, not even void.
  • Automatically called when creating an object: Every time an object is created using new, the constructor is automatically called.
  • Can be overloaded: Multiple constructors can be defined for the same class, but their parameter lists must be different (i.e., they constitute overloading).

Whether you define a constructor or not, all classes have constructors because Java automatically provides a default constructor. The access modifier of the default constructor is the same as the access modifier of the class (if the class is public, the constructor is also public; if the class is changed to protected, the constructor is also changed to protected).

Once you define your own constructor, the default constructor becomes invalid.

Example

Here is an example using a constructor:

class MyClass {
    int x;

    MyClass(int i) {
        x = i;
    }
}

You can call the constructor to initialize an object as follows:

ConsDemo.java File Code:

public class ConsDemo {
    public static void main(String[] args) {
        MyClass t1 = new MyClass(10);
        MyClass t2 = new MyClass(20);
        System.out.println(t1.x + " " + t2.x);
    }
}

The result is as follows:

10 20

For more content, refer to the next chapter: Java Constructors.

Variable Arguments (Varargs)

Starting from JDK 1.5, Java supports passing variable arguments of the same type to a method.

The declaration of a method's variable arguments is as follows:

typeName... parameterName

In the method declaration, after specifying the parameter type, add an ellipsis (...).

A method can only specify one variable argument, and it must be the last parameter of the method. Any regular parameters must be declared before it.

Example

VarargsDemo.java File Code:

public class VarargsDemo {
    public static void main(String[] args) {
        printMax(34, 3, 3, 2, 56.5);
        printMax(new double[]{1, 2, 3});
    }

    public static void printMax(double... numbers) {
        if (numbers.length == 0) {
            System.out.println("No argument passed");
            return;
        }
        double result = numbers;
        for (int i = 1; i  result) {
                result = numbers;
            }
        }
        System.out.println("The max value is " + result);
    }
}

The compilation and execution result of the above example is as follows:

The max value is 56.5
The max value is 3.0

The finalize() Method

The finalize method has been marked as deprecated in Java 9 and will be removed in future Java versions. It is recommended to use try-with-resources or java.lang.ref.Cleaner to manage resources.

Java allows defining a method that is called before an object is garbage collected (reclaimed). This method is called finalize(), and it is used to clean up the reclaimed object.

For example, you can use finalize() to ensure that a file opened by an object is closed.

Inside the finalize() method, you must specify the operations to be performed when the object is destroyed.

The general format of finalize() is:

protected void finalize() {
    // Finalization code here.
}

The keyword protected is a qualifier that ensures the finalize() method is not called by code outside of this class.

Of course, Java's memory reclamation can be automatically completed by the JVM. If you use it manually, you can use the above method.

Example

FinalizationDemo.java File Code:

public class FinalizationDemo {
    public static void main(String[] args) {
        Cake c1 = new Cake(1);
        Cake c2 = new Cake(2);
        Cake c3 = new Cake(3);

        c2 = c3 = null;
        System.gc(); // Invoke the garbage collector
    }
}

class Cake extends Object {
    private int id;

    public Cake(int id) {
        this.id = id;
        System.out.println("Cake Object " + id + " is created");
    }

    protected void finalize() throws java.lang.Throwable {
        super.finalize();
        System.out.println("Cake Object " + id + " is disposed");
    }
}

Run the above code, the output result is as follows:

$ javac FinalizationDemo.java
$ java FinalizationDemo
Cake Object 1 is created
Cake Object 2 is created
Cake Object 3 is created
Cake Object 3 is disposed
Cake Object 2 is disposed

Alternative: It is recommended to use the AutoCloseable interface in conjunction with the try-with-resources statement to automatically close resources. For example:

try (Resource res = new Resource()) {
    // Use the resource
} catch (Exception e) {
    e.printStackTrace();
}
← Java Files IoJava Regular Expressions β†’