首页 > 应用开发 > Java > Java 引用类型 & 值类型
1.值类型传值,引用类型传引用
Demo:
public class ReferDemo {
//public int x=10;
/**
* @param args
* primitive type: number boolean type;
* refer type :class 数组
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//值类型传值,引用类型传引用,不改变原值
int x=1;
set(1);
System.out.println("x:"+x);
String y="y";
set(y);
System.out.println("y:"+y);
//数组是引用类型
String[] a=new String[1];
a[0]="a[0]";
set(a);
System.out.println(a[0]); //out-print: "a[0]<----"
}
public static void set(int x){
x=x+1;
}
public static void set(String x){
x=x+"^_^";
}
public static void set(String[] s){
s[0]+="<----";
}
}
Output:
x:1 int 是值类型 primitive
y:y string 是特殊的引用类型,用法和值类型一致
a[0]<---- 数组是引用类型
2.并不是所有object都是按引用传地址的,比如:
Demo:
public class SwapParameter {
/**
* summary:
* 1.方法不能改变值类型参数的值
* 2.方法能改变对象类型参数的属性状态
* 3.方法不能将对象参数引用到一个新的对象
* ------------------------------------
原文《Core Java 8th.》
* This discussion demonstrates that the Java programming language does not use call by refernce for objects.
* Instead, [object reference are passed by value];
* A method cannot modify a parameter of primitive type(this is,number or boolean values).
* A method can change the state of an object parameter.
* A method cannot make an object parameter refer to a new object.
* @author Fly_Lv.
*
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Sts s1=new Sts("Lv");
Sts s2=new Sts("Fi");
System.out.println("Before swap()");
System.out.println("s1.name="+s1.name);
System.out.println("s2.name="+s2.name);
swap(s1,s2);
System.out.println("After swap()");
System.out.println("s1.name="+s1.name);
System.out.println("s2.name="+s2.name);
}
public static void swap(Sts s1,Sts s2){
Sts tmp=s1;
s1=s2;
s2=tmp;
}
}
class Sts{
protected String name;
public Sts(String name){
this.name=name;
}
}
Output:
Before swap()
s1.name=Lv
s2.name=Fi
After swap()
s1.name=Lv
s2.name=Fi
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/22050934/viewspace-1028525/ ,如需转载,请注明出处,否则将追究法律责任。