JAVA functions
Example 1 using of basic function:
public class Demo01 {
public static void main(String[] args) {
int sum = add(1,2);// call function;'1' and '2' are actual parameter
System.out.println(sum);
}
public static int add(int a, int b){
/*
‘public static’: modifier, to tell the compiler how to call the method
'int':type of return value
'add(formal parameter: int a, int b)':function name - CamelCase rule
*/
return a+b;
}
}
package method;
public class Demo02 {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
/*
(base) 192-168-1-104:src yanglimin$ cd method
(base) 192-168-1-104:method yanglimin$ javac Demo02.java
(base) 192-168-1-104:method yanglimin$ cd ../
(base) 192-168-1-104:src yanglimin$ java method.Demo02
(base) 192-168-1-104:src yanglimin$ java method.Demo02 LILAPE STUDIO
LILAPE
STUDIO
*/
Example 3 Variable arguments
When number of parameter is not sure, we can use variable arguments
You need to notice: the variable arguments should at the end of method parameter defenition. Here is an example
public void test(int a, int...b){//acceptable
}
public void test(int...b, int a){//unacceptable
}
Here is an example of using variable arguments:
package method;
public class Demo03 {
public static void main(String[] args) {
Demo03 demo03 = new Demo03();
demo03.test(1,3,4,5);// you can pass different number of parameter by using 'int...a' in your method
}
public void test(int...a){
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]/2);
}
}
}
Comments
Post a Comment