在 Java 中,String 是不可变对象,创建方式主要有以下几种:
String s1 = "hello";
new 关键字String s2 = new String("hello");
char[] chars = {'h', 'e', 'l', 'l', 'o'};
String s3 = new String(chars);
也可以指定范围:
String s4 = new String(chars, 0, 3); // "hel"
byte[] bytes = {104, 101, 108, 108, 111}; // hello
String s5 = new String(bytes);
可指定字符集:
String s6 = new String(bytes, StandardCharsets.UTF_8);
String s7 = "hel" + "lo"; // 编译期优化为 "hello"
运行时拼接:
String a = "hel";
String b = "lo";
String s8 = a + b; // 实际使用 StringBuilder
String.valueOf()String s9 = String.valueOf(123); // "123"
intern()(了解即可)String s10 = new String("hello").intern();
| 场景 | 推荐方式 |
|---|---|
| 普通字符串 | "xxx" |
| 动态内容 | + 或 StringBuilder |
| 避免重复对象 | 使用常量池 |
如果你愿意,我可以:
你想了解哪一个?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。