可能重复:
Java String.equals 与 ==
我是java新手,所以不要指望事情会很容易,但这让我完全震惊。为什么 if 语句不能正确评估:
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class StringMystery extends JFrame {
JTextArea txt = new JTextArea();
String string1 = "abcde";
String string2 = string1.substring(0,4);
public StringMystery() {
setLayout(null);
txt.setBounds(20, 20, 100, 100);
add(txt);
txt.setText(string2);
//string 2 is definitely equal to "abcd" but this doesn't evaluate:
if (string2 == "abcd"){
txt.setText("string2 = abcd");
}
}
public static void main(String[] args) {
StringMystery jtxt = new StringMystery();
jtxt.setSize(200,200);
jtxt.setTitle("String Mystery");
jtxt.setVisible(true);
}
}