当前位置:编程学习 > JAVA >>

Java中的值传递和引用传递

当一个变量最为一个参数传入方法内部的时候,会有两种不同的传递方式:值传递和引用传递。

值传递的特点:不管方法内部对传进去的参数作任何改变,也不会影响方法外部的变量的值


引用传递的特点:方法内部对传进去的参数作的改变也会影响方法外部的变量的值

 


那么哪些是值传递,哪些是引用传递呢?

基本类型(8种)的传递都是值传递
引用类型(除String外)都是引用传递
Strng比较特殊,它虽然是引用类型,但是却是值传递

 

通过一下例子来理解:

Student.java

[java]
package com.tianjf; 
 
public class Student { 
    private String name; 
 
    public Student(String name) { 
        super(); 
        this.name = name; 
    } 
 
    public String getName() { 
        return name; 
    } 
 
    public void setName(String name) { 
        this.name = name; 
    } 
 
    @Override 
    public String toString() { 
        return name; 
    } 

package com.tianjf;

public class Student {
 private String name;

 public Student(String name) {
  super();
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 @Override
 public String toString() {
  return name;
 }
}
Test.java

[java]
package com.tianjf; 
 
public class Test { 
     
    private static void changeInt(int i) { 
        i = 1; 
    } 
     
    private static void changeStudent(Student student) { 
        student.setName("李四"); 
    } 
     
    private static void changeString(String str) { 
        str = "456"; 
    } 
     
    public static void main(String[] args) { 
        int i = 0; 
        String str = "123"; 
        Student student = new Student("张三"); 
        System.out.println("Before change:\ni:" + i + "\n" + "student:" + student.toString() + "\n" + "str:" + str); 
         
        changeInt(i); 
        changeStudent(student); 
        changeString(str); 
        System.out.println("After change:\ni:" + i + "\n" + "student:" + student.toString() + "\n" + "str:" + str); 
    } 

package com.tianjf;

public class Test {
 
 private static void changeInt(int i) {
  i = 1;
 }
 
 private static void changeStudent(Student student) {
  student.setName("李四");
 }
 
 private static void changeString(String str) {
  str = "456";
 }
 
 public static void main(String[] args) {
  int i = 0;
  String str = "123";
  Student student = new Student("张三");
  System.out.println("Before change:\ni:" + i + "\n" + "student:" + student.toString() + "\n" + "str:" + str);
  
  changeInt(i);
  changeStudent(student);
  changeString(str);
  System.out.println("After change:\ni:" + i + "\n" + "student:" + student.toString() + "\n" + "str:" + str);
 }
}
运行结果: www.zzzyk.com

Before change:
i:0
student:张三
str:123
After change:
i:0
student:李四
str:123

 


从运行结果可以看出,int和String类型的值经过change方法后没有变,而student的值变了。

 作者:tianjf0514
 

 

 

 

 


 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,