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

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。

posted on 2017-09-29 22:02  GuaNiu9978  阅读(617)  评论(0)    收藏  举报

导航