首页 > 其他 > 详细

string和new string()的区别,以及equals与==的去别

时间:2017-09-29 23:46:12      阅读:322      评论:0      收藏:0      [点我收藏+]
import java.util.Scanner;
public class TestScanner
{
    public static void main(String[] args) 
    {   //Java会确保一个字符串常量只有一个拷贝
        String str1="hello";
        String str2="hello";
        //输出true
        System.out.println(" "+(str1==str2));
        //输出true
        System.out.println(" "+str1.equals(str2));

        //S1和S2指向不同的对象  new String() 创建的字符串不是常量,不能在编译期就确定,
        //所以new String() 创建的字符串不放入常量池中,它们有自己的地址空间。

        String S1=new String("hello");
        String S2=new String("hello");
        //输出false
        System.out.println(" "+(S1==S2));
        //输出true
        System.out.println(" "+S1.equals(S2));

       //str3和str4指向同一个对象
        String str3="hello";
        String str4=str3;
        //输出true
        System.out.println(" "+(str3==str4));
        //输出true
        System.out.println(" "+str3.equals(str4));
        

        


    }
}

总结:在比较字符串是否相同的时候尽量使用equals。

string和new string()的区别,以及equals与==的去别

原文:http://www.cnblogs.com/learning9978/p/7612965.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!