一、带参数方法的定义和调用
1.形参和实参:
- 形参:方法定义中的参数,等同于变量定义格式,例如:int number
- 实参:方法调用中的参数,等同于使用变量或常量,例如 10 number
2.带参数方法练习
public class MethodTest {
public static void main(String[] args) {
//使用常量方法调用
getMax(10,20);
//使用变量方法调用
int a = 10;
int b = 20;
getMax(a,b);
}
public static void getMax(int a,int b){
System.out.println((a > b)?a:b);
}
}
二、带返回值方法的定义和调用
1.带返回值方法的定义
方法定义时return后面的返回值与方法定义上的数据类型要匹配,否则程序将报错
2.带返回值方法调用
注意:方法的返回值通常会使用变量接收,否则该返回值将无意义
3.带返回值方法练习
public class MethodTest {
public static void main(String[] args) {
System.out.println(getMax(10,20));
}
public static int getMax(int a, int b){
if(a > b){
return a;
}else {
return b;
}
}
}
5.方法的注意事项
- 方法不能嵌套定义
- void表示无返回值,可以省略return,也可以单独的书写return,后面不加数据
三、方法重载
1.特点
- 重载仅对应方法的定义,与方法的调用无关,调用方式参照标准格式
- 重载仅针对同一个类中方法的名称与参数进行识别,与返回值无关,换句话说不能通过返回值来判定两个方法是否相互构成重载
2.方法重载练习
public class OverLoadTest {
public static void main(String[] args) {
System.out.println(compare(10,20));
System.out.println(compare((byte)10,(byte)10));
System.out.println(compare((short) 10,(short) 20));
System.out.println(compare(10L,20L));
}
public static boolean compare(int a, int b){
return a == b;
}
public static boolean compare(short a, short b){
return a == b;
}
public static boolean compare(long a, long b){
return a == b;
}
public static boolean compare(byte a, byte b){
return a == b;
}
}
三、方法的参数传递
1.方法参数传递(基本类型)
对于基本数据类型的参数,形式参数的改变,不影响实际参数的值
change方法调用完毕后,从栈内存中消失
再次调用main方法,输出还是100。main方法调用完成后也从栈内存中消失。
public class ArgsDemo1 {
public static void main(String[] args) {
int number = 100;
System.out.println("调用change方法前:" + number);
change(number);
System.out.println("调用change方法后:" + number);
}
public static void change(int number){
number = 200;
}
}
/*
调用change方法前:100
调用change方法后:100
*/
2.引用类型参数传递(引用类型)
对于引用类型的参数,形式参数的改变,影响实际参数的值
修改arr[1]
public class ArgsDemo2 {
public static void main(String[] args) {
int[] arr = {10, 20, 30};
System.out.println("调用change方法前:" + arr[1]);
change(arr);
System.out.println("调用change方法后:" + arr[1]);
}
public static void change(int[] arr){
arr[1] = 200;
}
}
/*
调用change方法前:20
调用change方法后:200
*/
案例:数组遍历
需求:设计一个方法用于数组遍历,要求结果是在一行的。
public class ArrayTest {
public static void main(String[] args) {
//静态初始化
int[] arr = {11,22,33,44,55};
printArray(arr);
}
public static void printArray(int[] arr){
System.out.print("[");
for (int i = 0;i < arr.length;i++){
if (i == arr.length - 1){
System.out.print(arr[i]);
}else {
System.out.print(arr[i] + ", ");
}
}
System.out.println("]");
}
}
//[11, 22, 33, 44, 55]
ystem.out.print(arr[i]);
}else {
System.out.print(arr[i] + ", ");
}
}
System.out.println("]");
}
}
//[11, 22, 33, 44, 55]
注:截图来自黑马程序员Java教程