可变个数的形参
JavaSE 5.0 中提供了Varargs(variable number of arguments)机制,允许直接定义能和多个实参相匹配的形参。从而,可以用一种更简单的方式,来传递个数可变的实参。
- 可变个数形参的方法
1.jdk 5.0新增的内容
2.具体使用:
2.1 可变个数形参的格式:数据类型 … 变量名
2.2 当调用可变个数形参的方法时,传入的参数的个数可以是:0个,1个,2个…
2.3可变个数形参的方法与本类中方法名相同,形参不同的方法之间构成重载。
2.4可变个数形参的方法与本类中方法名相同,形参类型也相同的数组之间不构成重载。即二者不可共存。
2.5可变个数形参在方法中的形参中,必须声明在末尾。
2.6可变个数形参在方法中的形参中,最多只能声明一个可变形参。
*/
public class MethodArgs {
public static void main(String[] args) {
MethodArgs test = new MethodArgs();
test.show(12);
// test.show("hell0");
// test.show("hello","world");
// test.show();
test.show(new String[] { "AA", "BB", "CC" });
}
public void show(int i) {
}
// public void show(String s){
// System.out.println("show(String)");
// }
public void show(String... strs) {
System.out.println("show(String ...strs)");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
}
// 此方法与上一方法不可共存
// public void show(String[] strs){
//
// }
public void show(int i, String... strs) {
}
//The variable argument type String of the method show must be the last parameter
// public void show(String... strs,int i,) {
//
// }
}
方法参数的值传递机制
- 关于变量的赋值
如果变量是基本数据类型,此时赋值的是变量所保存的数据值。
*如果变量是引用数据类型,此时赋值的是变量所保存的数据的地址值。
public class ValueTransferTest {
public static void main(String[] args) {
System.out.println("**********基本数据类型:***********");
int m = 10;
int n = m;
System.out.println("m = " + m + ", n = " + n);//10,10
n = 20;
System.out.println("m = " + m + ", n = " + n);//10,20
System.out.println("***********引用数据类型:********");
Order o1 = new Order();
o1.orderId = 1001;
Order o2 = o1; //赋值后,o1和o2的地址值相同,都指向了堆空间中同一个对象实体
System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " + o2.orderId);//1001,1001
o2.orderId = 1002;
System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " + o2.orderId);1002,1002
}
}
class Order{
int orderId;
}
方法的形参的传递机制
形参:方法定义时,声明的小括号内的参数
实参:方法调用时,实际传递给形参的数据
值传递机制:
如果参数是基本数据类型,此时实参赋值给形参的是实参真实存储的数据值。
如果参数是引用数据类型,此时实参赋值给形参的是实参存储数据的地址值
练习1
public class TransferTest3{
public static void main(String args[]){
TransferTest3 test=new TransferTest3();
test.first();
}
public void first(){
int i=5;
Value v=new Value();
v.i=25;
second(v,i);
System.out.println(v.i);
}
public void second(Value v,int i){
i=0;
v.i=20;
Value val=new Value();
v=val;
System.out.println(v.i+" "+i);
}
}
class Value {
int i= 15;
}
输出15 0 20
/*
* int[] arr = new int[10];
* System.out.println(arr);//地址值?
*
* char[] arr1 = new char[10];
* System.out.println(arr1);//地址值?
*/
public class ArrayPrint {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3};
//传进去的是一个Object的对象
System.out.println(arr);//地址值
char[] arr1 = new char[]{'a','b','c'};
//传进去的是一个数组,里面遍历数据了
System.out.println(arr1);//abc
}
}