Home  >  Article  >  Java  >  What is the function of return statement in java

What is the function of return statement in java

王林
王林forward
2020-07-09 16:46:223825browse

What is the function of return statement in java

The return statement in Java has two functions, namely:

(Recommended tutorial: java entry program)

1. Return the value of the type specified by the method (this value is always determined);

2. End the execution of the method (just a return statement).

The return statement is used in methods with non-void return value types. It can not only return basic types, but also objects (including user-defined classes).

(Video tutorial recommendation: java video tutorial)

Example:

/**
* Created by IntelliJ IDEA.
* User: leizhimin
* Date: 2007-12-3
* Time: 8:54:28
* Java中的return语句使用总结
*/
public class TestReturn {
    public static void main(String args[]) {
       TestReturn t = new TestReturn();
        t.test1();
        t.test2();
    }

    /**
     * 无返回值类型的return语句测试
     */
    public void test1() {
        System.out.println("---------无返回值类型的return语句测试--------");
        for (int i = 1; ; i++) {
            if (i == 4) return;
            System.out.println("i = " + i);
        }
    }

    /**
     * 有返回值类型的return语句测试
     * @return String
     */
    public String test2(){
        System.out.println("---------有返回值类型的return语句测试--------");
        return "返回一个字符串";
    }
}

Run result:

---------无返回值类型的return语句测试--------
i = 1
i = 2
i = 3
---------有返回值类型的return语句测试--------

The above is the detailed content of What is the function of return statement in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete