package ff;public class TestString {
static String a = "hello"; static String b = "Hello"; static String c = new String("hello"); public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = new String("hello"); System.out.println(a == TestString.a);
System.out.println(b == TestString.b);
System.out.println(c == TestString.c); }
}
==是比较内存相等不,我现在是提问的是,a == TestString.a为TRUE,就是说static String a = "hello";与String a = "hello";内存相等。那static String b = "Hello";和String b = "hello";内存怎么不相等?那static String c = new String("hello");和String c = new String("hello");内存怎么不相等?高手分析下。
static String a = "hello"; static String b = "Hello"; static String c = new String("hello"); public static void main(String[] args) {
String a = "hello";
String b = "hello";
String c = new String("hello"); System.out.println(a == TestString.a);
System.out.println(b == TestString.b);
System.out.println(c == TestString.c); }
}
==是比较内存相等不,我现在是提问的是,a == TestString.a为TRUE,就是说static String a = "hello";与String a = "hello";内存相等。那static String b = "Hello";和String b = "hello";内存怎么不相等?那static String c = new String("hello");和String c = new String("hello");内存怎么不相等?高手分析下。
因为,我感觉这个String 不是可以看作是..一个类吗.//
我感觉这点,,就是事例化和不事例化的问题.
如果要用equls.. 的确是好理解的.就是比较..,值的相等与否的问题...\
这个"=="还要深刻的研究的../
static String b = "Hello"; // 构建一个内容为 Hello 的 String 实例,我们称之为 y 实例,将类静态变量指向 y 实例。
static String c = new String("hello"); // 将 x 实例作为参数传给 String 类的构造参数,构造出另外一个 String 实例 x1。String a = "hello"; // 将本地变量 a 指向 x 实例。
String b = "hello"; // 将本地变量 b 指向 x 实例。
String c = new String("hello"); // 将 x 实例作为参数传给 String 类的构造参数,构造出又一个 String 实例 x2。
static String b = "Hello";先是在栈空间创建b这个Hello(大写的H)
String b = "hello";然后创建这个b的时候,它会先在栈空间里找,看能否找到,如果找不到,再创建hello(小写的H)
String类型的==比较内容Hello!=helloc的那个是比较对象的引用,分别在堆空间二个地址,怎么可以有相等呢
1、 public class TestString {
public static void main(String[] args) {
String s1 = "Monday";
String s2 = "Monday";
if (s1 == s2)
System.out.println("s1 == s2");
else
System.out.println("s1 != s2");
}
} 输出:s1 == s2public class TestString {
public static void main(String[] args) {
String s1 = "Monday";
String s2 = new String("Monday");
if (s1 == s2)
System.out.println("s1 == s2");
else
System.out.println("s1 != s2");
if (s1.equals(s2))
System.out.println("s1 equals s2");
else
System.out.println("s1 not equals s2");
}
} 程序输出:
s1 != s2
s1 equals s2 原因:程序在运行的时候会创建一个字符串缓冲池
当使用 s2 = "Monday" 这样的表达是创建字符串的时候,程序首先会
在这个String缓冲池中寻找相同值的对象,在第一个程序中,s1先被
放到了池中,所以在s2被创建的时候,程序找到了具有相同值的 s1
将 s2 引用 s1 所引用的对象"Monday"
第二段程序中,使用了 new 操作符,他明白的告诉程序:
“我要一个新的!不要旧的!”与是一个新的"Monday"Sting对象被创
建在内存中。他们的值相同,但是位置不同,一个在池中游泳
一个在岸边休息。
String ss = new String("hello");不管串池中有没有,都在堆区新建一个对象