--What is a method?
-A collection of multiple programs, named as one process (function).
-Since it is described in functional units, the range of correction can be limited. -Since thousands to tens of thousands of lines of source code are required at the development site, it can be described as simply as possible using methods. (The outlook for the program is better and easier to understand)
java
public static return type method name(argument){
Specific processing to be executed after the method is called
}#The return type describes the data type of the value of the result of processing in the method. If the processing result is a numerical value, it will be int, and if it is a character string, it will be String.
#For example
public static int score(argument){
processing...
}
#When there is a method called score and the result of the score is returned to the caller, the processing result(Score)Is a number, so it becomes an int.
#Method call
Method name(argument); #The return value is not available.
#Receiving the return value
Variable type Variable name=Method name(argument); #You can use the return value in a variable.
#The method is not executed just by defining it. The process of the method is executed only after it is called.
--What is the return value?
The value (data) returned from the called method to the calling method is called the return value or return value.
java
return Return value; #This will allow you to return a value to the calling method.
#This return value is the execution result of the method.
You can pass a value from the caller when calling the method.
java
public static void main(String[] arg) {
hello("Okamura"); #helloメソッドを呼び出している。Okamuraという文字列のデータ(Actual argument)Is passed to the hello method.
hello("Yamamoto"); #Same as above
hello("Sasaki"); #Same as above
}
public static void hello(String name) { #When calling the method, Okamura is assigned to the String type variable name as a formal argument.
System.out.println(name + "Hi,"); #The data assigned to the variable name is output here.
}
#The execution result is
>Mr. Okamura, Hello
Mr. Yamamoto, Hello
Sasaki, Hello
#Will be.
#You can pass multiple arguments. In that case, a comma(,)Separate the arguments with.
.....main method(...){ #It's really simplified. I'm sorry for the trouble.
add(10, 20); #10 to add method,Pass the number 20 as an argument.
}
.....add method(int a, int b){ #add methodは引数を受け取り、aに10,20 is assigned to b.
Processing using arguments...
}
#The point to note here is that the first numerical value 10 described as an argument is assigned to a.
#()Which variable is assigned to is determined by the arrangement in.
-Define a method with the same name. Also called overloading. -Even if the method name is the same, it can be overloaded if the data type and the number of arguments are different.
Recommended Posts