传值(传的是副本,相当于我又创建了一个相同的值)
// 基本数据类型
public class ParamChangeValue {
public static void main(String[] args) {
int s = 1;
System.out.println("args = [" + s + "]");
change(s);
System.out.println("args = [" + s + "]");
}
private static void change(int i){
i = i* 5;
}
}
传引用(引用的是同一个内存地址的值)
// 对象
public class ObjectChangeValue {
public static class Score{
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public static void main(String[] args) {
Score score = new Score();
score.setValue(1);
System.out.println("args = [" + score.getValue() + "]");
change(score);
System.out.println("after args = [" + score.getValue() + "]");
}
private static void change(Score score){
score.setValue(2);
}
}
从结果中我们可以看到score实例的value值被修改了,因为传引用后指向的是同一个地址,修改的实际上也就是这个地址上的值,另外要注意一点的是如果对象被重新创建或赋值为null,即new会重新指向其他对象,不影响其原对象的值。
总结:基本类型(byte,short,int,long,double,float,char,boolean)为传值;对象类型(Object,数组,容器)为传引用;String、Integer、Double等immutable类型因为类的变量设为final属性,无法被修改,只能重新赋值或生成对象。当Integer作为方法参数传递时,对其赋值会导致原有的引用被指向了方法内的栈地址,失去原有的的地址指向,所以对赋值后的Integer做任何操作都不会影响原有值。
public class Test {
public static void main(String[] args) {
Student xiaowang = new Student("xiaowang", 12);
Student xiaoli=xiaowang;
System.out.println(xiaowang);
xiaowang.eat();
xiaowang.setName("王八蛋");
System.out.println("-------------------");
xiaoli.eat();
System.out.println(xiaoli);
}
}
class Student{
private String name;
private int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public void eat(){
System.out.println(name+"吃的是红薯");
}
}
参考文章:https://blog.csdn.net/weixin_36759405/article/details/82764339