字符串String数据类型的探讨

java中,String类型不是基本类型,而是引用类型,也就是说,需要用new来创建对象,即String str=new String();但是实际上也可以直接用等号来赋值,即String str="happy new year!"。所以它是一种特殊的类型。两种赋值方式有什么区别呢?用程序来测试一下。

Public static void main(String[] args){
    String s1="hello!";
     String s2="hello!";
    String s3=new String("hello!");
     String s4=new String("hello!");
    System.out.println(s1==s2);
     System.out.println(s1==s3);
     System.out.println(s3==s4);
}
     对比四个变量的引用地址, 显示结果为:true false false
    这是因为s1与s2引用了同一块地址,而s3、s4每次使用new都另外建立了新的地址,与s1、s2的不是同一块地址。所以有了这样的结果。通常情况下,直接用等号给string赋值。
 
参考资料:中软国际教学视频第4章

猜你喜欢

转载自spral.iteye.com/blog/2261521
今日推荐