[Explanation of Interview Questions] What is the return value of a method in Java? What are the types of methods?

Sometimes the blog content will change. The first blog is the latest, and other blog addresses may not be synchronized. Check it carefully.https://blog.zysicyj.top

First blog address [1]

Interview question manual [2]

Series article address [3]


1. What is the return value of a method?

The return value of a method refers to the result returned by the method after the method is called. It can be any type of data, including basic data types and reference data types.

2. What are the types of methods?

Methods in Java can be divided into the following types:

  • Method without return value : The method has no return value and is void declared using keywords. This type of method is usually used to perform some operations without returning results, such as printing information, modifying object status, etc.
  • Basic data type return value method : that is, the method returns a value of a basic data type, such as int , double , boolean etc. By specifying the return type when declaring the method, and using return statements to return specific values.
  • Reference data type return value method : that is, the method returns a value of a reference data type, such as a class, interface, array, etc. You also need to specify the return type when declaring the method, and use return statements to return specific objects or arrays.
  • Multiple return value methods : Methods in Java can only return one value, but you can use container classes (such as List, Map) or custom classes to encapsulate multiple return values, and then use them as the return value of the method.

Below is sample code for each type of method:

// 无返回值方法
public void printMessage(String message) {
    System.out.println(message);
}

// 基本数据类型返回值方法
public int add(int a, int b) {
    return a + b;
}

// 引用数据类型返回值方法
public String getFullName(String firstName, String lastName) {
    return firstName + " " + lastName;
}

// 多个返回值方法(使用自定义类封装)
public class Result {
    private int sum;
    private String message;

    public Result(int sum, String message) {
        this.sum = sum;
        this.message = message;
    }

    // getter and setter methods

}

public Result calculate(int a, int b) {
    int sum = a + b;
    String message = "The sum of " + a + " and " + b + " is " + sum;
    return new Result(sum, message);
}

3. Summary

方法的返回值指的是在调用方法后,该方法所返回的结果。Java 中的方法可以分为无返回值方法、基本数据类型返回值方法、引用数据类型返回值方法和多个返回值方法。无返回值方法使用void关键字声明,基本数据类型和引用数据类型返回值方法需要在方法声明时指定返回类型,并使用return语句返回具体的值或对象。多个返回值方法可以使用容器类或自定义类封装多个返回值。

参考资料

[1]

首发博客地址: https://blog.zysicyj.top/

[2]

面试题手册: https://store.amazingmemo.com/chapterDetail/1685324709017001

[3]

系列文章地址: https://blog.zysicyj.top/categories/技术文章/后端技术/系列文章/面试题精讲/

本文由 mdnice 多平台发布

Guess you like

Origin blog.csdn.net/njpkhuan/article/details/133552005