2013-11-09 74 views
-1

我有这段代码,为什么bo3 = st1 == st2给出true?比较两个字符串给出true

他们是不是在内存中的不同位置,并通过==我们比较的位置是否 它是否相同!

此外,如果有什么问题,请指出我。感谢你们。

public static void main(String[] args) { 

    String st1 = "HELLO"; 
    String st2 = "HELLO"; 
    String st3 = "hello"; 


    int comp1 = st1.compareTo(st2); // equal 0 
    int comp2 = st1.compareTo(st3); // -32 

    boolean bo1 = st1.equals(st2); //true 
    boolean bo2 = st1.equals(st3); // false , if ignoreCase will be true 

    boolean bo3 = st1==st2; //true ??????????? should not be true 
    boolean bo4 = st1 == st3; //false 


    int ind1 = st1.indexOf("L"); // 2 
    int ind2 = st1.lastIndexOf("L"); // 3 

    boolean con = st1.contains("LLO"); //true 


    System.out.println(bo3); 
} 

虽然我有另外一个代码,当我进入“玛丽”,结果: 相同的名称和不等于

public static void main(String [] args) { 

    Scanner keyboard = new Scanner(System.in); 
    System.out.print("What is your name? "); 
    String name = keyboard.next(); 

    if (name.equals("Mary")) 
     System.out.print("Same name"); 
    else 
     System.out.print("Different name"); 

    if (name == "Mary") 
     System.out.println("equal"); 
    else 
     System.out.println("not equal"); 
} 
+1

Java的字符串添加到一个字符串池,以减少对内存的使用,所以ST1和ST2在你的第一个例子将指向相同的内存位置。 –

回答

0

这与==行为是有些coincidential在您使用"test"创建你的字符串。字符串中的许多==行为都是特定于实现的。只有equals()被保证能够比较字符串值。

比较字符串时,总是使用equals()如果可能的话,作为字符串保证被扣留。当你使用这样的文字时,编译器把这个字符串放到字符串池中,并且将代码中的所有相同的文字字符串指向同一个String对象。

当你创建级联或构造函数的字符串

,同样未必是真实的:

String test="test"; 
String test2=new String("test"); 
String t="te"; 
String s="st" 
String test3=t+s; 

有没有保证test==test2test2==test3,但equals()它仍然是真实的。