直接上例子:
class string{
public static void main(String[] args) {
//方法区
String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2);//true
System.out.println(s1.equals(s2));//true
System.out.println("-----------------------------");
//堆区
String s3 = new String("def");
String s4 = new String("def");
System.out.println(s3 == s4);//false
System.out.println(s3.equals(s4));//true
}
}
String s1 = "abc";
String s2 = "abc";
这种方式,字符串会存储在JVM方法区的String常量池中
所以s1、s2指向的都是用一个内存地址!
String s3 = new String("def");
String s4 = new String("def");
这种方式,字符串会存储在JVM的堆内存中
因为new开辟的内存都在堆中!
建议以后String判断相等都用equals()方法判断,百分百不会错!