Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

equals() 與 ==

// Orz.java

import java.io.*;

public class Orz{

public static void main(String args[])throws IOException{

String str, str1="-1";

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

str=br.readLine(); //這裡輸入-1且按下enter.

if(str=="-1") //這個敘述false??

System.out.println("str is == -1");

else if(str==str1) //這個也不等??

System.out.println("str is == str1");

else if(str.equals("-1"))

System.out.println("str is equals -1");

System.out.println(str);

br.close();

}

}

===========================================================

說明:在輸入時我輸入-1然後按enter,

可是輸出結果為何跳過if(str=="-1")跟else if(str==str1),

輸出的畫面是:str is equals -1.

問題:operator== 跟 equals()有什麼不同?

為何前面的兩個if-else if會是false?

2 Answers

Rating
  • ?
    Lv 6
    2 decades ago
    Favorite Answer

    == 運算在Java中被用來比較兩個名稱是否參考至同一物件,所以不可以用==來比較兩個字串的內容是否相同,例如:

    String str1 = new String("caterpillar");

    String str2 = new String("caterpillar");

    System.out.println(str1 == str2);

    上面會顯示false的結果,因為str1與str2是分別參考至不同的字串物件,如果要比較兩個(字串)物件是否相同,您要使用equals()方法,例如:

    String str1 = new String("caterpillar");

    String str2 = new String("caterpillar");

    System.out.println(str1.equals(str2));

    這樣子結果才會顯示所想要的比較結果:true。

    更多的資料還可以參考。。。

    http://caterpillar.onlyfun.net/Gossip/JavaGossip-V...

  • 2 decades ago

    如果用int當作宣告的變數會不會比較簡單呢~?

Still have questions? Get your answers by asking now.