A method (some prefer to call it a function) is a reusable piece of code.

: Notebook: This article is filed under “blog”

: Keyboard: The sample code in this article is archived under: “Javacore”

Use of methods

Method definition

Method definition syntax format:

[modifier] Return value type method name ([parameter type parameter name]){... Method body...returnThe return value. }Copy the code

Example:

public static void main(String[] args) {
    System.out.println("Hello World");
}
Copy the code

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

  • Modifiers – Modifiers are optional and tell the compiler how to call the method. Defines the access type for the method.
  • Return value type – The return value type indicates the data type of the result returned after the method has finished executing. If no value is returned, set to void.
  • Method name – is the actual name of the method. The method name and parameter list together form the method signature.
  • Parameter type – The parameter is like a placeholder. When a method is called, the value is passed to the parameter. The parameter list refers to the type, order, and number of parameters of a method. Arguments are optional, and methods can contain no arguments.
  • Method body – The method body contains concrete statements that define the functionality of the method.
  • return– Must return the same data type as the value returned when the method was declared. In a void method, the return statement is optional; if you write a return, it must bereturn;In this form.

Method call

When a program calls a method, control of the program is given to the called method. Returns control to the program when the return statement of the called method executes or when the method body closes parentheses.

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

  • Return value methods – Return value methods are usually used to assign a value to a variable or to evaluate an expression.
int larger = max(30, 40);
Copy the code
  • No-return method – A no-return method can only be a statement.
System.out.println("Hello World");
Copy the code

Recursive calls

Java supports recursive invocation of methods (that is, the method invocation itself).

Note:

  • Recursive methods must have explicit termination conditions.
  • Try to avoid using recursive calls. Recursive calls can cause stack overflows if not handled properly.

Example of Fibonacci sequence (a typical recursive algorithm) :

public class RecursionMethodDemo {
    public static int fib(int num) {
        if (num == 1 || num == 2) {
            return 1;
        } else {
            return fib(num - 2) + fib(num - 1); }}public static void main(String[] args) {
        for (int i = 1; i < 10; i++) {
            System.out.print(fib(i) + "\t"); }}}Copy the code

The method parameters

In programming languages such as C/C++, method parameter passing generally takes two forms:

  • Value passing – The parameters passed by value are called parameters. When a value is passed, changes to the parameter passed in the method do not take effect outside the method.
  • Pass by reference – Parameters passed by reference are called arguments. When a reference is passed, changes in the method that are passed in the parameter take effect outside the method.

So, what about in Java?

There is only value passing in Java.

Example 1:

public class MethodParamDemo {
    public static void method(int value) {
        value =  value + 1;
    }
    public static void main(String[] args) {
        int num = 0;
        method(num);
        System.out.println("num = [" + num + "]");
        method(num);
        System.out.println("num = [" + num + "]"); }}// Output:
// num = [0]
// num = [0]
Copy the code

Example 2:

public class MethodParamDemo2 {
    public static void method(StringBuilder sb) {
        sb = new StringBuilder("B");
    }

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("A");
        System.out.println("sb = [" + sb.toString() + "]");
        method(sb);
        System.out.println("sb = [" + sb.toString() + "]");
        sb = new StringBuilder("C");
        System.out.println("sb = [" + sb.toString() + "]"); }}// Output:
// sb = [A]
// sb = [A]
// sb = [C]
Copy the code

Description:

In both of the above examples, the value changed in the method does not take effect externally, whether the underlying data type or reference type is passed into the method.

Java copies values directly into methods for primitive data types; For reference data types, the reference address of the current object is copied and then passed, so it is also value passed.

Read more:

Illustration of parameter passing in Java

Method modifier

As mentioned earlier, Java method modifiers are optional and tell the compiler how to call the method. Defines the access type for the method.

Java methods have several modifiers, so let’s take a look at each one:

Access control modifier

The levels of access permission control are as follows:

Public > protected > Package access (without any keywords) > privateCopy the code
  • public– Any class can be accessed.
  • Package access– Package access without any keywords. It means that all other classes in the current package are accessible, but classes in other packages are not.
  • protected– Indicates that subclasses are accessible, and that other classes within the same package are also accessible, even if they are not subclasses.
  • private– Indicates that no other classes are accessible.

static

bestaticMethods that are decorated are called static methods.

The main differences between static methods and ordinary instance methods are as follows:

  • Class names can be used when static methods are invoked externally. Method name, or object name. Method name. Instance methods have only the latter. That is, you can call a static method without creating an object.

  • When a static method accesses a member of the class, it only allows access to a static member (that is, static member variables and static methods), but not to instance member variables and instance methods. Instance methods do not have this limitation.

Static methods are commonly used in various utility classes and factory method classes.

final

Methods modified by final cannot be overridden by subclasses (Override).

Final method example:

public class FinalMethodDemo {
    static class Father {
        protected final void print(a) {
            System.out.println("call Father print()");
        };
    }

    static class Son extends Father {
        @Override
        protected void print(a) {
            System.out.println("call print()"); }}public static void main(String[] args) {
        Father demo = newSon(); demo.print(); }}// An error will be reported during compilation
Copy the code

Description:

In the example above, if the Father class defines a final method print(), its subclass cannot Override the final method, or it will compile an error.

default

Starting with JDK8, you can define the default method in Interface. The default method can only be used on the Interface.

In the interface isdefaultThe modified method is called the default method, and any class that implements the interface that does not Override the method inherits it without having to implement it.

The default method syntax was created to add new functionality to the thousands of classes in the existing Java class library without having to redesign them. For example, there is a handy stream() method in the Collection class in JDK8, which is decorated with default. The List and Set subclasses of the Collection inherit the stream() method directly without having to add it to each subclass.

Example of the default method:

public class DefaultMethodDemo {
    interface MyInterface {
        default void print(a) {
            System.out.println("Hello World"); }}static class MyClass implements MyInterface {}

    public static void main(String[] args) {
        MyInterface obj = newMyClass(); obj.print(); }}// Output:
// Hello World
Copy the code

abstract

beabstractMethods that decorate are called abstract methods and cannot have entities. Abstract methods can only appear in abstract classes.

Example abstract method:

public class AbstractMethodDemo {
    static abstract class AbstractClass {
        abstract void print(a);
    }

    static class ConcreteClass extends AbstractClass {
        @Override
        void print(a) {
            System.out.println("call print()"); }}public static void main(String[] args) {
        AbstractClass demo = newConcreteClass(); demo.print(); }}// Outpu:
// call print()
Copy the code

synchronized

Synchronized is used for concurrent programming. Synchronized modified methods allow only one thread to execute at a time.

In Java’s synchronized containers (Vector, Stack, HashTable), you’ll see a lot of synchronized methods. However, keep in mind that synchronized is not a good option in Concurrent Java programming, and in most cases we’ll opt for a lighter lock.

Special methods

In Java, there are special methods that can be used in specific scenarios.

The main method

The main method in Java is a special static method because all Java programs start with the public static void main(String[] args) method.

There are a lot of newbies who use main all the time but don’t know what args in main are for. In fact, this is used to receive input arguments from the receive command line.

Example:

public class MainMethodDemo {
    public static void main(String[] args) {
        for (String arg : args) {
            System.out.println("arg = [" + arg + "]"); }}}Copy the code

Executed in sequence

javac MainMethodDemo.java
java MainMethodDemo A B C
Copy the code

The console prints out the parameters:

arg = [A]
arg = [B]
arg = [C]
Copy the code

A constructor

Any class has a constructor that sets the state of an instance of the class when it is initialized.

Every class has a constructor. If no constructors are explicitly defined for the class, the Java compiler will provide a default constructor for the class.

When creating an object, at least one constructor is called. The constructor name must have the same name as the class, and a class can have more than one constructor.

public class ConstructorMethodDemo {

    static class Person {
        private String name;

        public Person(String name) {
            this.name = name;
        }

        public String getName(a) {
            return name;
        }

        public void setName(String name) {
            this.name = name; }}public static void main(String[] args) {
        Person person = new Person("jack");
        System.out.println("person name is "+ person.getName()); }}Copy the code

Note that the constructor can use the private modifier as well as public, in which case the class cannot call the constructor to instantiate the object. This is often used in the singleton pattern of the design pattern.

Varargs method

Starting with JDK5, Java supports passing mutable arguments of the same type to a method. In the method declaration, add an ellipsis after the parameter type… . Only one variable parameter can be specified in a method, and it must be the last parameter of the method. Any ordinary arguments must be declared before it.

Example of variable parameter method:

public class VarargsDemo {
    public static void method(String... params) {
        System.out.println("params.length = " + params.length);
        for (String param : params) {
            System.out.println("params = [" + param + "]");
        }
    }

    public static void main(String[] args) {
        method("red");
        method("red"."yellow");
        method("red"."yellow"."blue");
    }
}
// Output:
// params.length = 1
// params = [red]
// params.length = 2
// params = [red]
// params = [yellow]
// params.length = 3
// params = [red]
// params = [yellow]
// params = [blue]
Copy the code

The finalize () method

Finalize is called before objects are destructed (collected) by garbage collector to clean up collected objects.

Finalize is defined in java.lang.Object, which means that every Object has a method. This method is called when the GC starts and the object is reclaimed.

Finalizers () are often unpredictable, dangerous, and generally unnecessary. Using finalization methods can lead to erratic behavior, reduced performance, and portability issues.

Keep in mind that you should avoid using Finalizers (). Never use it as a destructor in C/C++. The reason: The Finalizer thread competes with our main thread, but because it has a lower priority and gets less CPU time, it never catches up with the main thread. So an OutOfMemoryError may eventually occur.

Read more:

The following two articles describe in detail the possible problems caused by Finalizer () and their causes.

  • Memory overflow caused by Java Finalizer. Procedure
  • Memory leaks caused by overloading Finalize

Overwrite and overload

Override means that a subclass defines a method with the same name as the parent class, but access rights must be considered when overriding the method. The method overridden by a subclass cannot have more stringent access rights than the parent class.

If you want to access the methods of the parent class, you can use the super keyword.

Overwrite example:

public class MethodOverrideDemo {
    static class Animal {
        public void move(a) {
            System.out.println("Moving"); }}static class Dog extends Animal {
        @Override
        public void move(a) {
            super.move();
            System.out.println("Run"); }}public static void main(String[] args) {
        Animal dog = newDog(); dog.move(); }}// Output:
/ / movement
/ / run
Copy the code

Method Overload means that the methods have the same name but different types or numbers of parameters. Method calls with different functions can be completed by the different number and type of parameters passed.

Note:

Overloading must be methods whose arguments are not exactly the same. Java will not compile if the method’s arguments are identical except for the return values.

Reload examples:

public class MethodOverloadDemo {
    public static void add(int x, int y) {
        System.out.println("x + y = " + (x + y));
    }

    public static void add(double x, double y) {
        System.out.println("x + y = " + (x + y));
    }

    public static void main(String[] args) {
        add(10.20);
        add(1.0.2.0); }}// Output:
// x + y = 30
// x + y = 3.0
Copy the code

summary



The resources

  • Java Programming ideas
  • JAVA Core Technologies (Volume 1)
  • Head First Java
  • Illustration of parameter passing in Java
  • Memory overflow caused by Java Finalizer. Procedure
  • Memory leaks caused by overloading Finalize