参数的值传递
实参必须与方法中次你故意的参数在次序和数量上匹配,在类型上兼容.
类型兼容是指不需要经过显式的类型转换,实参的值就可以传递给形参.如将int型的实参值传递给double型形参.
当调用方法时,实参的值传递给形参,这个过程称为按值传递.如果是实参是变量而不是直接量,则将该变量的值传递给形参.无论形参在方法中是否改变,该变量都不受影响.
package welcome; /* * void方法 */ public class TestVoidMethod { public static void main(String[] args) { System.out.print("The grade is "); printGrade(78.5); // 对void方法的调用必须是一条语句. System.out.print("The grade is "); printGrade(59.5); } public static void printGrade(double score){ // printGrade方法是一个void方法,它不返回任何值 if(score < 0 || score > 100){ System.out.println("Invalid score"); return; // return用于终止方法,并返回到到方法的调用者 } if(score >= 90.0){ System.out.println("A"); }else if(score >= 80.0){ System.out.println("B"); }else if(score >= 70.0){ System.out.println("C"); }else if(score >= 60.0){ System.out.println("D"); }else{ System.out.println("F"); } } }
package welcome; /* * 带返回值的方法 */ public class TestReturnGradeMethod { public static void main(String[] args) { System.out.println("The grade is " + getGrade(78.5)); System.out.println("The grade is " + getGrade(59.5)); } public static char getGrade(double score){ if(score >= 90){ return 'A'; }else if(score >= 80){ return 'B'; }else if(score >= 70){ return 'C'; }else if(score >= 60){ return 'D'; }else{ return 'F'; } } }
package welcome; /* * Java传参机制是按值传递(pass-by-value) * 当调用方法时,实参的值传递给形参,这个过程称为按值传递. * 如果是实参是变量而不是直接量,则将该变量的值传递给形参.无论形参在方法中是否改变,该变量都不受影响. */ public class Increment { public static void main(String[] args) { int x = 1; System.out.println("Before the call, x is " + x); increment(x); System.out.println("After the call, x is " + x); } public static void increment(int n){ n++; System.out.println("n inside the method is " + n); } }
package welcome; public class TestPassByValue { public static void main(String[] args) { int num1 = 1; int num2 = 2; System.out.println("Before invokint the swap method, num1 is " + num1 + " num2 is " + num2); swap(num1, num2); System.out.println("After invoking the swap method, num1 is " + num1 + " num2 is " + num2); } public static void swap(int n1, int n2){ System.out.println(" Inside the swap method"); System.out.println(" Before swapping n1 is " + n1 + " n2 is " + n2); int temp = n1; n1 = n2; n2 = temp; System.out.println(" After swapping n1 is " + n1 + " n2 is " + n2); } }