1. JAVA方法用于完成一段特定的逻辑和功能以便于被调用执行,定义在类或者对象中。
package com.langtao.method;
public class Demo1 {
public static void main(String[] args) {
int sum = 0;
sum = add(1,2);
System.out.println(sum);
int max = max(10, 10);
System.out.println(max);
}
public static int add(int a, int b){
return a + b;
}
public static int max(int num1, int num2){
int result = 0;
if(num1 == num2){
System.out.println("These two integer numbers are equal to each other.");
return 0;//the return line can be used to terminal the method.
}else if(num1 > num2){
result = num1;
}else{
result = num2;
}
return result;
}
2. 方法的重载:在一个类中定义多个命名相同的方法,参数的个数、类型或者顺序不同,那么在调用方法时,会自动根据实参的模式去匹配方法。
package com.langtao.method;
public class Demo2 {
public static void main(String[] args) {
int i = 1;
int j = 2;
int k = 3;
int maxInt2 = max(i, j);
System.out.println("The max integer is: " + maxInt2);
int maxInt3 = max(i, j, k);
System.out.println("The max integer among three is: " + maxInt3);
double a = 3.0;
double b = 5.0;
double maxDouble2 = max(a, b);
System.out.println("The max number of the two double ones is: " + maxDouble2);
}
public static int max(int m, int n){
int result = 0;
if(m > n){
result = m;
}else {
result = n;
}
return result;
}
public static int max(int m, int n, int p){
int result = 0;
int tmpMax = 0;
if(m >= n){
tmpMax = m;
if(tmpMax >= p){
result = tmpMax;
}else{
result = p;
}
}else{
tmpMax = n;
if(tmpMax <=p ){
result = p;
} else{
result = tmpMax;
}
}
return result;
}
public static double max(double m, double n){
double result = 0;
if(m > n){
result = m;
}else {
result = n;
}
return result;
}
}
3.命令行参数
package com.langtao.method;
public class Demo3 {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
System.out.println("args[" + i + "] is: " + args[i]);
}
}
}
使用javac命令编译java文件:在命令行窗口,java文件目录下进行
使用java命令执行class时,在src/目录下,执行时指定包名com.langtao.method.Demo3
4.可变长参数
1)定义方法的形式参数为“数据类型+...+参数名“,例如:method(int... a);
2)一个方法中只能有且只有一个变长参数,变长参数本质是一个数组(变长参数中的实参必须统一),变长参数必须放在参数列表的末尾。
package com.langtao.method;
public class Demo4 {
public static void main(String[] args) {
Demo4 d = new Demo4();
d.max(1, 2, 4.0);
d.max(23,45.6,3984.6,9999,342,651);
double m[] = {11, 23.6, 892.4};
d.max(m);
}
protected void max(double... numbers){
double result = 0;
for (int i = 0; i < numbers.length; i++) {
if(numbers[i] > result){
result = numbers[i];
}
}
System.out.println("The max number is: " + result);
}
}
5. 递归:边界条件;前阶段;返回阶段
package com.langtao.method;
public class Demo5 {
public static void main(String[] args) {
Demo5 d = new Demo5();
System.out.println(d.diGui(5));
}
public int diGui(int n){
if(n == 1){
return 1;
}else{
return n * diGui(n-1);
}
}
}