温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java String 如何创建字符串

发布时间:2026-10-06 00:05:27 来源:亿速云 阅读:100 作者:小樊 栏目:编程语言

在 Java 中,String(字符串) 的创建方式主要有以下几种,每种方式在内存和性能上略有区别。


一、使用字符串字面量(推荐、最常用)

String s1 = "hello";

特点:

  • 使用 字符串常量池(String Pool)
  • 如果常量池已存在相同字符串,不会新建对象,直接复用
  • 效率高,节省内存
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); // true(同一对象)

二、使用 new 关键字(不推荐频繁使用)

String s2 = new String("hello");

特点:

  • 在 堆内存 中创建一个新的 String 对象
  • 同时常量池中也会有 “hello”(如果之前没有)
  • == 比较的是不同对象
String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1 == s2); // false

三、通过字符数组创建

char[] chars = {'h', 'e', 'l', 'l', 'o'};
String s3 = new String(chars);

四、通过字节数组创建(常用于 IO、网络)

byte[] bytes = {104, 101, 108, 108, 111}; // hello
String s4 = new String(bytes);

指定编码(推荐):

String s5 = new String(bytes, StandardCharsets.UTF_8);

五、通过 StringBuilder / StringBuffer

适合 频繁拼接字符串

StringBuilder sb = new StringBuilder();
sb.append("hello");
sb.append(" world");
String s6 = sb.toString();

六、通过 valueOf()

String s7 = String.valueOf(123);

七、intern() 方法(进阶)

String s = new String("hello").intern();
  • 强制使用字符串常量池
  • 面试常考

✅ 推荐使用方式总结

场景 推荐方式
普通字符串 String s = "xxx";
拼接字符串 StringBuilder
明确新对象 new String()
编码转换 new String(bytes, charset)

如果你愿意,我也可以:

  • 讲 String、StringBuilder、StringBuffer 区别
  • 讲 String 不可变原理
  • 讲 面试常问的 String 面试题

你想了解哪一个?

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手