java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言, 是由 Sun Microsystems 公司于 1995 年 5 月推出的 Java 程序设计语言和 Java 平台 (即 JavaEE(j2ee), JavaME(j2me), JavaSE(j2se)) 的总称
这篇文章主要介绍了 java 中函数的参数传递详细介绍的相关资料, 需要的朋友可以参考下
java 中函数的参数传递
总结:
1. 将对象 (对象的引用) 作为参数传递时传递的是引用 (相当于指针) 也就是说函数内对参数所做的修改会影响原来的对象
2. 当将基本类型或基本类型的包装集作为参数传递时, 传递的是值也就是说函数内对参数所做的修改不会影响原来的变量
3. 数组 (数组引用)) 作为参数传递时传递的是引用 (相当于指针) 也就是说函数内对参数所做的修改会影响原来的数组
4.String 类型 (引用) 作为参数传递时传递的是引用, 只是对 String 做出任何修改时有一个新的 String 对象会产生, 原来的 String 对象的值不会做任何修改(但是可以将新的对象的 引用赋给原来的引用, 这样给人的表面现象就是原来的对象变了, 其实没有变, 只是原来指向它的引用指向了新的对象)
- package StringTest;
- class A {
- int a = 1;
- char b = 'A';
- public A() {}
- public A(int _a, char _b) {
- this.a = _a;
- this.b = _b;
- }
- public String toString() {
- return "a=" + this.a + ",b=" + this.b;
- }
- }
- public class ReferenceTest {
- public static A changeA(A classa) {
- classa.a = 2;
- classa.b = 'B';
- return classa;
- }
- public static String changeString(String str) {
- System.out.println(str.hashCode());
- str = str.toLowerCase();
- System.out.println(str.hashCode());
- return str;
- }
- public static int changeint(int a) {
- a = a + 1;
- return a;
- }
- public static Integer changeInteger(Integer a) {
- a = new Integer(9);
- return a;
- }
- public static int[] changeintarray(int a[]) {
- a[0] = 10;
- return a;
- }
- public static void printArray(int a[]) {
- for (int i = 0; i < a.length; i++) {
- System.out.print(a[i] + " ");
- }
- System.out.println();
- }
- public static void main(String[] args) {
- // 自定义的对象传递的是引用
- A a = new A();
- A b = changeA(a);
- System.out.println(a);
- System.out.println(b);
- System.out.println("----------------------");
- //String 对象作为参数传递的也是引用(只是 String 对象的值不能变, 每一个修改 String 对象的值都会重新创建一个新的 String 对象用以保存修改后的值, 原来的值不会变)
- String str1 = "HUHUALIANG";
- System.out.println(str1.hashCode());
- String str2 = changeString(str1);
- System.out.println(str2.hashCode());
- System.out.println(str1);
- System.out.println(str2);
- System.out.println("----------------------");
- // 基本类型是值传递
- int inta = 8;
- int intb = changeint(inta);
- System.out.println(inta);
- System.out.println(intb);
- System.out.println("----------------------");
- // 基本类型的包装集作为参数传递的是值而不是引用
- Integer c = new Integer(1);
- Integer d = changeInteger(c);
- System.out.println(c);
- System.out.println(d);
- System.out.println("----------------------");
- // 数组传递的是引用
- int[] arraya = {
- 0,
- 1,
- 2,
- 3
- };
- int[] arrayb = changeintarray(arraya);
- printArray(arraya);
- printArray(arrayb);
- }
- }
运行结果:
- a=2,b=B
- a=2,b=B
- ----------------------
- 711139030
- 711139030
- 226046678
- 226046678
- HUHUALIANG
- huhualiang
- ----------------------
- 8
- 9
- ----------------------
- 1
- 9
- ----------------------
- 10 1 2 3
- 10 1 2 3
来源: http://www.phperz.com/article/18/0214/359380.html