return 关键字

概述

return 关键字用于从方法中返回值,并终止方法的执行。

语法格式

return;              // void方法中返回
return value;        // 返回值
return expression;   // 返回表达式结果

基本用法

public class ReturnExample {
    // 返回基本类型
    public static int add(int a, int b) {
        return a + b;
    }

    // 返回对象
    public static String getName() {
        return "张三";
    }

    // void方法中的return
    public static void processData(int data) {
        if (data < 0) {
            System.out.println("无效数据");
            return; // 提前结束方法
        }
        System.out.println("处理数据:" + data);
    }

    // 多个返回点
    public static String getGrade(int score) {
        if (score >= 90) return "A";
        if (score >= 80) return "B";
        if (score >= 70) return "C";
        if (score >= 60) return "D";
        return "F";
    }

    public static void main(String[] args) {
        System.out.println("加法结果:" + add(5, 3));
        System.out.println("姓名:" + getName());

        processData(-1);
        processData(10);

        System.out.println("成绩:" + getGrade(85));
    }
}

使用场景

public class ReturnUsage {
    // 早期返回模式
    public boolean validateUser(String username, String password) {
        if (username == null || username.isEmpty()) {
            return false;
        }
        if (password == null || password.length() < 6) {
            return false;
        }
        // 主要验证逻辑
        return username.equals("admin") && password.equals("123456");
    }

    // 返回数组
    public int[] getRange(int start, int end) {
        if (start > end) {
            return new int[0]; // 返回空数组
        }
        int[] result = new int[end - start + 1];
        for (int i = 0; i < result.length; i++) {
            result[i] = start + i;
        }
        return result;
    }
}

return关键字是控制方法执行流程的重要手段,合理使用可以让代码更清晰。

powered by Gitbook© 2025 编外计划 | 最后修改: 2025-07-28 16:25:54

results matching ""

    No results matching ""