10、Java方法
Java的方法类似于其他语言的函数,是一段用来完成特定功能的代码片段,声明格式:
[修饰符1 修饰符2 ...] 返回值类型 方法名 (形式参数列表){
Java语句; ... ... ...
}
形式参数:在方法被调用时用于接收外界传入的数据。
实参:调用方法时实际传给方法的数据。
返回值:方法在执行完毕后返还给调用它的环境的数据。
返回值类型:事先约定的返回值的数据类型,如无返回值,必须给出返回值类型void。
Java语言中使用下述形式调用方法:对象名.方法名(实参列表)
实参的数目、数据类型和次序必须和所调用方法声明的形参列表匹配,
return 语句终止方法的运行并指定要返回的数据
Java 中进行函数调用中传递参数时,遵循值传递的原则:
基本类型传递的是该数据值的本身。
引用类型传递的是对对象的引用,而不是对象本身。
TestMethod.java
public class TestMethod {
public static void main (String[] args) {
m();
m2(2);
m3('3', 4);
m4(4, 6);
int i = m4(4, 6);
System.out.println(i);
}
public static void m() {
//return;
System.out.println("ok");
System.out.println("hello");
}
public static void m2(int i) {
if (i > 3)
return;
System.out.println(i);
}
public static void m3(int i, int j) {
System.out.println(i + j);
}
public static int m4(int i, int j) {
return i > j ? i : j;
}
}
C:\Users\root\Desktop>javac TestMethod.java
C:\Users\root\Desktop>java TestMethod
ok
hello
2
55
6
TestMethod2.java
public class TestMethod2 {
public static void main (String args[]) {
System.out.println(method(5));
}
public static int method(int n) {
if (n == 1)
return 1;
else
return n*method(n-1);
}
}
TestMethod3.java
public class TestMethod3 {
public static void main(String args[]) {
System.out.println(f(50));
}
public static int f(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return f(n - 1) + f(n - 2);
}
}
}
public class Fab {
public static void main (String[] args) {
System.out.println(f(5));
}
public static long f(int index) {
if (index == 1 || index == 2) {
return 1;
}
long f1 = 1L;
long f2 = 1L;
long f = 0;
for (int i=0; 1<index-2; i++) {
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
}
}

浙公网安备 33010602011771号