String类型:
String 为引用类型,特殊的被final修饰,在创建时会在String缓冲池中查看,若存在该String对象,则直接调用,且地址与缓冲池中的地址一样,(使用new方法的话,对象的地址一定不同) 否则将创建一个新的对象地址,代码介绍如下:
public static void main(String[] args) {
String str1="aaaa"; //String缓冲池 中加入"aaaa"
String str2="aaaa"; // 直接从缓冲池取 "aaaa" 地址与str1一样
System.out.println(str1==str2); //true
System.out.println(str1.equals(str2)); //true
String str3=new String("aaaa"); // 直接创建新的"aaaa" 地址与str1不一样
System.out.println(str3==str1); //false
System.out.println(str3.equals(str1)); //true
str3=str3.intern();// 检查String缓冲池是否有"aaaa" 有的话就直接 返回池中的"aaaa"对象 ,否则将其加入String缓冲池
System.out.println(str3==str1); //true
System.out.println(str3.equals(str1)); //true
}
}
程序举例并解析
1.
程序举例源码,(一个笔试题)
public class Example {
String str = new String( "good");
char[] ch = { 'a', 'b' , 'c' };
public static void main(String args[]) {
Example ex = new Example();
ex.change( ex. str, ex .ch );
System. out.print(ex .str + " and ");
System. out.print(ex .ch );
}
public void change(String str , char ch[])
{
str = "test ok" ;
ch[0] = 'g';
}
}
打印结果为:
good and gbc
解析:
String类型为 引用类型,数组为引用类型,在调用change()方法是,因为String为特殊的引用类型,被finall修饰,所以str="test ok"执行时,在String缓冲池中会新建一个“test ok”的引用对象,而形参str将会指向这个新的“test ok”新的引用地址,在change()方法完成后,str又指向开始的“good”应用地址,所以打印是不会改变值
而ch[] 的在change()方法中地址没有发生变化,修改了原地址指向的堆里的值,所以在打印是指向的值发生了变化,也就是说str是改变了新的一个string类型的引用对象副本,而原来的str没有发生变化,这里有两个String对象,在chage()方法完成后,新的string对象“销毁”,str地址不变
2.
public class ValueOrReference {
String str=new String("good"); //new方式创建字符串对象会在堆栈开辟空间
char[] ch ={'a' ,'b' ,'c' };
int a =4;
public static void main(String[] args) {
ValueOrReference ex = new ValueOrReference();
ex.change( ex. str,ex .ch ,ex .a );
System. out.println(ex .str );// str没变
System. out.println(ex .ch );//
System. out.println(ex .a );
}
private void change(String str, char[] ch, int a ) {
str="test ok" ;
ch = new char []{'1','2','3'};
a=9;
}
}
打印结果:
good
abc
4
解析:
String类同上,数组因为指向了新的数组对象:
ch
=
new
char
[]{
'1'
,
'2'
,
'3'
}; 所以改变的是ch的副本,最后打印时候,值为ch开始指向的对象的值,而int 也是一个道理
3.
要想结果发生变化修改如下:
String str=new String( "good");//new方式创建字符串对象会在堆栈开辟空间
char[] ch ={'a' ,'b' ,'c' };
int a =4;
public static void main(String[] args) {
ValueOrReference ex = new ValueOrReference();
ex.change();
System. out.println(ex .str );
System. out.println(ex .ch );//
System. out.println(ex .a );
}
private void change() {
str="test ok" ;
ch = new char []{'1','2','3'};
a=9;
}
打印结果:
test ok
123
9