SoFunction
Updated on 2025-03-09

Examples of several usages of return statements in java

In Java,returnThe statement is used to return a value from the current method (if the method has a return value type) or to directly end the execution of the method (if the method returns type isvoid)。

1. Methods with return value types

When a method declares the return value type (exceptvoidAny type other thanintStringObjectetc.), it must be used inside the method bodyreturnStatement to return a value that matches the declared return value type.

For example, here is a simple method to calculate the sum of two integers and return the result:

public class Main {
    public static int addNumbers(int num1, int num2) {
        int sum = num1 + num2;
        return sum;
    }

    public static void main(String[] args) {
        int result = addNumbers(3, 5);
        ("The sum of the two numbers is:" + result);
    }
}

existaddNumbersIn the method:

  • First calculatenum1andnum2and store the result insumin variable.
  • Then usereturnThe statement returnedsumvalue. becauseaddNumbersThe return value type declared by the method isint, so the returnsumValue (alsointType) matches the return value type of the method.

existmainIn the method, theaddNumbersmethod and assign the returned result toresultvariable, finally print out.

2. Return in advance (multi-condition judgment scenario)

In some methods, it may be determined whether to return the result in advance based on different criteria. For example, the following is a method to determine whether an integer is an even number, and if it is an even number, it returnstrue, otherwise returnfalse

public class Main {
    public static boolean isEven(int num) {
        if (num % 2 == 0) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        int number = 4;
        boolean result = isEven(number);
        ("Is this number even number:" + result);
    }
}

existisEvenIn the method:

  • First passifVerificationnumDivide by2Is the remainder of0. If so, it meansnumIt is an even number, then use itreturnReturn statement in advancetrue, the method execution ends here, and the subsequent code will not be executed again.
  • ifnumDivide by2The remainder of0, then execute to the end of the methodreturn falsestatement, returnfalse

This early return method is very useful when dealing with complex conditional judgment logic, making the code clearer and more efficient.

3. Return object

In addition to returning the basic data type, you can also return objects. For example, here is a simple class and method that creates and returns aPersonObject:

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
         = name;
         = age;
    }

    public String getName() {
        return name;
    }

    public int Age() {
        return age;
    }
}

public class Main {
    public static Person createPerson(String name, int age) {
        return new Person(name, age);
    }

    public static void main(String[] args) {
        Person person = createPerson("Alice", 25);
        ("The person created is:" + () + ", Age is:" + ());
    }
}

existcreatePersonIn the method, usereturnThe statement returns a newly createdPersonObject. becausecreatePersonThe return value type declared by the method isPerson, so the returned object matches the return value type of the method.

4. The method return type is void

When the return value type of a method is declared asvoidhour,returnThe statement can still be used, but its purpose is to end the execution of the method in advance without returning any value.

For example, here is a method that prints some information and then ends the method ahead of time:

public class Main {
    public static void printMessage() {
        ("This is a message.");
        return;
    }

    public static void main(String[] args) {
        printMessage();
    }
}

existprintMessageIn the method, a message is first printed, and thenreturnThe statement ends the execution of the method in advance. Although herereturnThe statement does not return any value, but it serves to terminate the operation of the method early when needed.

Will the return statement end the execution of the entire program?

  • whenreturnStatement in a nonmainWhen a method (normal method) is used internally, it will only end the execution of the current method, and will not end the entire program.
    public class Main {
        public static int add(int a, int b) {
            return a + b;
        }
        public static void main(String[] args) {
            int result = add(3, 5);
            ("turn out:" + result);
            ("Program continues to execute");
        }
    }
  • In this example,addIn the methodreturnThe statement just returnsa + bThe result and endaddExecution of the method.mainThe code in the method will continue to be executed and retrievedaddAfter the result of the method, the printout will continue to be printed and output "Program Continue Execution".

existmainThe internal situation of the method

  • whenreturnThe statement ismainWhen the method is used internally, it will end the execution of the entire program. becausemainThe method is the entry point of the Java program, whenmainWhen the method ends, the program ends.
    public class Main {
        public static void main(String[] args) {
            ("Program Begins");
            return;
            ("This line of code will not be executed");
        }
    }

    In thismainIn the method,returnAfter the statement prints "Program Start", the entire program ends running, so the subsequent "This line of code will not be executed" will not be output. However, in practical applications,mainIn the methodreturnStatements are usually used to return a value that represents the execution status of a program (e.g.0Indicates normal ending), and in some complex program structures, it may be determined whether to end the program run in advance based on the conditional judgment.

Attachment: How to return multiple values ​​in Java

In Java, a method can only return one value. But multiple values ​​can be returned in different ways, for example:

  • Using an array or collection: You can save multiple values ​​in an array, list, or other collection, and then return the array or collection as the return value of the method.
public static List<Integer> getMultipleValues() {
    List<Integer> values = new ArrayList<>();
    (1);
    (2);
    (3);
    return values;
}
  • Use Custom Objects: You can define a custom object with multiple values ​​and then return the object as the return value of the method.
public class CustomObject {
    private int value1;
    private int value2;
    
    public CustomObject(int value1, int value2) {
        this.value1 = value1;
        this.value2 = value2;
    }
    
    public int getValue1() {
        return value1;
    }
    
    public int getValue2() {
        return value2;
    }
}

public static CustomObject getMultipleValues() {
    return new CustomObject(1, 2);
}
  • Using Map: You can use Map to store multiple key-value pairs and then return that Map as the return value of the method.
public static Map<String, Integer> getMultipleValues() {
    Map<String, Integer> values = new HashMap<>();
    ("value1", 1);
    ("value2", 2);
    return values;
}

These are some common methods that can be used to return multiple values. Depending on the specific needs, select the appropriate method to return multiple values.

Summarize

This is the end of this article about several examples of the use of return statements in java. For more related content on return usage in java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!