Home > Java > Javagetting Started > body text

What is the function of return statement in java

王林
Release: 2020-07-09 16:46:22
forward
3885 people have browsed it

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 "返回一个字符串";
    }
}
Copy after login

Run result:

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

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!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template