In Java,return
The 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 (exceptvoid
Any type other thanint
、String
、Object
etc.), it must be used inside the method bodyreturn
Statement 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); } }
existaddNumbers
In the method:
- First calculate
num1
andnum2
and store the result insum
in variable. - Then use
return
The statement returnedsum
value. becauseaddNumbers
The return value type declared by the method isint
, so the returnsum
Value (alsoint
Type) matches the return value type of the method.
existmain
In the method, theaddNumbers
method and assign the returned result toresult
variable, 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); } }
existisEven
In the method:
- First pass
if
Verificationnum
Divide by2
Is the remainder of0
. If so, it meansnum
It is an even number, then use itreturn
Return statement in advancetrue
, the method execution ends here, and the subsequent code will not be executed again. - if
num
Divide by2
The remainder of0
, then execute to the end of the methodreturn false
statement, 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 aPerson
Object:
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:" + ()); } }
existcreatePerson
In the method, usereturn
The statement returns a newly createdPerson
Object. becausecreatePerson
The 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 asvoid
hour,return
The 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(); } }
existprintMessage
In the method, a message is first printed, and thenreturn
The statement ends the execution of the method in advance. Although herereturn
The 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?
- when
return
Statement in a nonmain
When 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,
add
In the methodreturn
The statement just returnsa + b
The result and endadd
Execution of the method.main
The code in the method will continue to be executed and retrievedadd
After the result of the method, the printout will continue to be printed and output "Program Continue Execution".
exist
main
The internal situation of the method
- when
return
The statement ismain
When the method is used internally, it will end the execution of the entire program. becausemain
The method is the entry point of the Java program, whenmain
When 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 this
main
In the method,return
After 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,main
In the methodreturn
Statements are usually used to return a value that represents the execution status of a program (e.g.0
Indicates 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!