Declare a method that has a Java return value with the return value data type

What is the return value? The value output by the program .

For more information, From the IT terminology dictionary that makes you feel like "I understand" and "I don't understand" Please refer to What is the return value . It is illustrated in an easy-to-understand manner.

Here, we will actually explain using a program.

Remember this much and go home!
If there is a return valueReturn data typeDeclare with!

Program Overview-sample1- It is a program that calls the ʻaverage ()` method from the `main ()` method and displays the average of 1 and 2. The `main ()` method has no return value, so it is declared as a void type. The ʻaverage ()` method cannot be declared as a void type because it has a return value. If there is a return value, declare it with return value data type .

Let's take a look at the sample code

sample1.java



1 public class sample1 {
2   public static void main(String[] args) {
3     double number = average(1,2);
4     System.out.print(number);
5   }
6   static double average(int a, int b) {
7     double x = (a + b) / 2.0;
8     return x;
9   }
10}

Output </ b> 1.5

Points to note Since the return value is `1.5`, the data type of the return value is double type .
3rd line: Since the return value is returned as double type, `number` is also defined as double type . Line 6: Declare the data type of the ʻaverage ()` method as double type (= return data type) .

What are the arguments and return value? The argument (value to be entered in the program) is the `1,2` entered in the` main () `method. The return value (value output by the program) is the `1.5` output from the ʻaverage ()` method. It will be.

Summary Immediately after I started studying Java, I didn't understand the relationship between the return value and the method, and it took a long time to understand. I hope you find this article useful.

Recommended Posts