1、字符串的创建
字面量直接赋值
先去常量池中找有没有这个字符串,有就直接指向常量池中该字符串;没有直接创建
String str1 = "hello" ;
String str2 = "hello" ;
String str3 = "world";
new 创建
new一个字符串时,做了两件事。首先在堆中生成了该字符串对象,然后去看常量池中有没有该字符串,如果有就不管了,没有就往常量池中添加一个
String str1 = new String("hello");
String str2 = new String("hello");
String str3 = new String("world");
在堆中创建三个对象,常量池中两个共5个。
小结:两种创建方式一个在堆中,一个在常量池中。
2、字符串拼接
(1)常量拼接
String str = "hello"+"world";
//两边都是常量,在编译阶段会自动拼接变成
String str = "helloworld";
直接去常量池找 “helloworld”,有就直接指向它,没有就在常量池创建。
(2)有final的拼接