日期:2014-05-20  浏览次数:20737 次

==是比较内存相等不,我现在是提问的是,a == TestString.a为TRUE,就是说static String a = "hello";与String a = "hello";内存相等。那static String b = "Hello";和Str
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 b = "Hello";和String b = "hello";内存怎么不相等?

因为"hello"和"Hello"本来就不一样。

new 关键字,就是开辟一块新内存,不会和原来的相等。
------解决方案--------------------
System.out.println(a == TestString.a); 的确相等...因为,static String a = "hello"; 这个只是创建了一个想int 样的数据类型..并没有创建对象,..也就不指向heap中的堆...只在栈中存在..所以这两者用该是相等的...

System.out.println(b == TestString.b); 这个也一样了..
因为,我感觉这个String 不是可以看作是..一个类吗.//
我感觉这点,,就是事例化和不事例化的问题.
如果要用equls.. 的确是好理解的.就是比较..,值的相等与否的问题...\
这个"=="还要深刻的研究的../



------解决方案--------------------
Java code
static String a = "hello"; // 构建一个内容为 hello 的 String 实例,我们称之为 x 实例,将类静态变量指向 x 实例。
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";和String b = "hello";内存怎么不相等?
static String b = "Hello";先是在栈空间创建b这个Hello(大写的H)
String b = "hello";然后创建这个b的时候,它会先在栈空间里找,看能否找到,如果找不到,再创建hello(小写的H)
String类型的==比较内容Hello!=hello

c的那个是比较对象的引用,分别在堆空间二个地址,怎么可以有相等呢
------解决方案--------------------
给你看看下面的代码吧,
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 == s2

public 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 

原因:程序在运行的时候会创建一个字符串缓冲池