首页 > 编程语言 >Java String类

Java String类

时间:2024-11-13 13:46:13浏览次数:1  
标签:Java String s1 System println public out

public class DemoTest {
    public static void main(String[] args) {

        /**
         * String类型是不可变的:不可变对象,意味着一旦进行修改,就会产生新的对象
         */
        String s1 = "123";
        System.out.println(System.identityHashCode(s1));
        s1 = "hello"; // s1已经是一个新的对象
        System.out.println(System.identityHashCode(s1));

        /**
         * 常量池
         */
        String s2 = "hello";
        String s3 = "hello";
        System.out.println(s2 == s3); // true

        String str4 = "abc";
        String str5 = new String("abc");
        System.out.println(str4 == str5); // false
        System.out.println(str4.equals(str5)); // true

        String str6 = new String("abc");
        String str7 = new String("abc");
        System.out.println(str6 == str7); // false
        System.out.println(str6.equals(str7)); // true
    }
}

 

// 返回各种类型的 value 的 String
public class Test {
    public static void main(String[] args) {
        char[] chs = {'A', 'B', '我', '是', '谁'};

        String s = String.valueOf(chs);
        System.out.println("s = " + s);

        String s1 = String.valueOf(chs, 0, 2);
        System.out.println("s1 = " + s1);

        Object obj = "你好啊";
        String s2 = String.valueOf(obj);
        System.out.println("s2 = " + s2);

    }
}

 

// 任意数据类型和 "字符串" 进行拼接,结果都是字符串
public class Test {
    public static void main(String[] args) {
        int num = 123456;
        String s = num + "";
        System.out.println("s = " + s);

        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);

        String str = list + "";
        System.out.println(str);
    }
}

 

标签:Java,String,s1,System,println,public,out
From: https://www.cnblogs.com/ReturnOfTheKing/p/18543752

相关文章