paremeters and Arguments
Information can be passed to methods as parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called car as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name.
public class Main {
static void myMethod(String car) {
System.out.println(car + "2023");
}
public static void main(String[] args) {
myMethod("Lucid");
myMethod("Tesla");
myMethod("Benz");
myMethod("BMW");
}
}
< multiple Parameters >
You can have as many parameters as you like
public class Main {
static void myMethod(String car, int year) {
System.out.println(car + "was founded in" + year );
}
public static void main(String[] args) {
myMethod("Lucid", 2007);
myMethod("Tesla", 2003);
myMethod("Benz", 1967);
myMethod("BMW", 1916);
}
}
Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
< Return Values >
The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method.
You can also store the result in a variable (recommended, as it is easier to read and maintain)
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int result = myMethod(9, 8);
System.out.println(result);
}
}
'Java' 카테고리의 다른 글
java - overriding (0) | 2023.03.13 |
---|---|
java - overloading (0) | 2023.03.13 |
java - Constructors (0) | 2023.03.13 |
java - Methods (1) | 2023.03.13 |
Java - Recursive Funtion (0) | 2023.03.03 |