两个关于字符串的经典例子

时间:2022-04-25
本文章向大家介绍两个关于字符串的经典例子,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

示例1:

==运算符

public static void test(){
String x = "hello";
String y = "world";
String a = "helloworld";
System.out.println("x==hello:"+(x=="hello"));
System.out.println("a==helloworld:"+(a=="hello"+"world"));
System.out.println("a==x+y:"+(a==(x+y)));
}

结果:

x == hello:true a == helloworld:true a == x+y:false

双引号内的字符串是放在常量池里的,当双引号内再次出现与原来字符串相同内容时,jvm不会创建新对象,只是将引用指向了常量池里原来就存在的那个String对象,这与用new创建不同,用new的话将在堆中创建一个新对象,不管在堆中有没有相同内容的对象。因此,对System.out.println("x==hello:"+(x=="hello"));“hello”所在的地址与x引用所指向的地址相同,输出true;

hello”+“world“在编译器内就已经确定了,即为已存在常量池中的以a作为引用的对象,仍输出true;

而x+y属引用相加,这在编译时是不能确定的,在执行期间将由x+y得出的“helloworld”放入堆中(而不是常量池),因此输出false。

示例2:

对象引用

public class TestRef{
public static void main(String[] args){
StirngBuffer a = new StringBuffer("a");
StringBuffer b = new StringBuffer("b");
append(a,b);
System.out.println(a.toString()+","+b.toString());
b = a;
System.out.println(a.toString()+","+b.toString());
}
public static void append(StringBuffer a,StringBuffer b){
a.append(b);
b = a;
}
}

结果: ab,b ab,ab 第一个为什么输出的为什么不是ab,ab呢,根据有关值传递与引用传递的理论,得出这样的结论:两个StringBuffer对象的引用传递到append方法中,方法中的a,b其实是不同于main()方法中的a,b引用的,但他们都分别指向同一个对象,通过append()方法中的a.append(b),使a指向的对象变成ab,而方法中b=a只是将append()中的b引用指向ab,而main()方法中的b引用仍指向原来的对象,即b,需要在main()中通过b=a,使main()中b引用指向ab,方能输出ab,ab。