String a = new String("abc"); String a1 = "abc"; 2个String a = new String("abc"); String a1 = new String("abc"); 2个String a = "abc"; String a1 = "abc"; 1个
的确 诚如 Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
int j = 6;我想我有两个整数型变量
2个对象
2个对象一个是在栈中间动态存放"abc" 一个是引用 存放 指向"abc"的地址。2个语句+起来总共是3个变量 2个引用同时指向"abc"
new String("abc")又一个
String a1="abc"; 这句没有新建,只是把a1指向第一个。
我是这样认为的。
a1则是在“字符串常量池”中生成的
所以是2个
String s=new String("abc");
String a="abc";
String b=a;
System.out.println(a==b);//True
System.out.println(a.equals(s));//true
System.out.println(a==s);//false
String a1 = "abc";
2个String a = new String("abc");
String a1 = new String("abc");
2个String a = "abc";
String a1 = "abc";
1个
String a1 = "abc"; //常量池中的对象
两个对象, 但是hashcode应该一样, 因为jvm内部应该只有一个"abc", 但是"abc"应该是被两个对象所引用,
和String s=new String("abc");
String s1 = s;
不一样, 这里是只有一个对象, 但是该对象有两个引用
创建了2个对象
String a1="abc";
指向一个对象,并没有创建对象
如果没有记错的话,上次人家问的是运行时,创建了几个String对象,
由于以上两句的对象是在编译期间就生成好的,所以不计算在内故 0 个
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
是两个String a1="abc";
是一个
两个对象的值都是'abc',不同的内存地址
String a=new String("abc");
是两个
String a1="abc";
只是一个引用池中已建好的"abc"对象,如是新的才创建
可以用以下程序证明:
public class TestString5 {
public static void main(String [] args){
String s1=new String("abc"); //栈内存的s1指向堆内存中的"abc"对象
String s2="abc"; //栈内存的s2指向堆内存中的"abc"对象
if(s1==s2){ //比较两个对象的引用是否相同
System.out.println("one");
}else{
System.out.println("two");
}
}程序结果是:two
说明两个对象的引用不一样
结果表明:虽然两个两个引用指向的对象的内容一样,但是两个对象是在堆内存中的不同位置,引用不同就说明它们存在的地址不一样