In-depth explanation of void method in Java

1.1 Basic introduction

void is a keyword in java. It means nothing is returned. We often use it in the development process. For example, when a method does not need a return value, we can use the void keyword, and it is also the void keyword in the main method. .

    public static void getName() {
        String name = "username";
        System.out.println(name);
    }
    public static void main(String[] args) {

    }
1.2 What is void?

First of all, we know that java is a strongly typed language. From the declaration syntax of the method, we can see that each method must have a return value, and the return value type of the method needs to be determined. When the definition method is modified with void, it means nothing. Does not return, it can be seen that void should also be regarded as a data type; and we know that the commonly used data types in java include 8 basic data types, reference types, etc.;

So what type should the void modifier correspond to? In fact, void corresponds to a Vod class:

package java.lang;

/**
 * The {@code Void} class is an uninstantiable placeholder class to hold a
 * reference to the {@code Class} object representing the Java keyword
 * void.
 *
 * @author  unascribed
 * @since   JDK1.1
 */
public final
class Void {

    /**
     * The {@code Class} object representing the pseudo-type corresponding to
     * the keyword {@code void}.
     */
    public static final Class<Void> TYPE = Class.getPrimitiveClass("void");

    /*
     * The Void class cannot be instantiated.
     */
    private Void() {}
}

The Void class is modified with final, indicating that it cannot be extended, and the constructor is private and cannot be instantiated;

The Void class is a non-instantiable placeholder class that holds a reference to a Class object that represents the Java keyword void.

1.3 How to terminate void-modified methods

If you want to terminate execution anywhere in the method, you can use return without any return value

    public void getName() {
        String name = "username";
        if(name != null)
            return;
        System.out.println(name);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325558845&siteId=291194637