作為 Codegym 大學課程一部分的導師授課片段。報名參加完整課程。


“我想告訴你一些關於在 Java 中比較變量的知識。

“您已經知道最簡單的比較運算符——小於 (<) 和大於 (>)。”

“是的。”

“還有等於 (==) 和不等於 (!=) 等運算符。以及小於或等於 (<=) 和大於或等於 (>=)。”

“現在這變得有趣了。”

“請注意,Java 中沒有 =< 或 => 運算符!”

= 符號用於賦值操作。 這就是為什麼使用兩個等號 (==) 來測試相等性。要檢查變量是否不相等,請使用!=運算符。”

“我懂了。”

“在 Java 中使用 == 運算符比較兩個變量時,我們正在比較變量的內容。”

“因此,對於原始變量,比較它們的值。”

“對於引用變量比較引用。假設我們有相同但不同的對象。因為對它們的引用不同,所以比較會表明它們不相等,即比較結果將為引用的比較將為僅當兩個引用都指向同一個對象時。

“為了比較對象的內部內容,我們使用特殊的equals方法。即使您沒有聲明它們,編譯器也會將此方法(以及 Object 類的所有方法)添加到您的類中。讓我舉幾個例子: “

代碼 解釋
1個
int a = 5;
int b = 5;
System.out.println(a == b);
比較原始類型。
true將顯示在屏幕上。
2個
Cat cat1 = new Cat("Oscar");
Cat cat2 = cat1;
System.out.println(cat1 == cat2);
比較參考資料
true將顯示在屏幕上。
兩個變量都存儲對同一對象的引用。
3個
String s = new String("Mom");
String s2 = s;
System.out.println(s == s2);
比較參考資料
true將顯示在屏幕上。
兩個變量都存儲對同一對象的引用。
4個
Cat cat1 = new Cat("Oscar");
Cat cat2 = new Cat("Oscar");
System.out.println(cat1 == cat2);
比較參考資料
false將顯示在屏幕上。
這兩個變量引用相同的 Cat 對象,但不是同一個。
5個
String s = new String("Mom");
String s2 = new String("Mom");
System.out.println(s == s2);
比較參考資料
false將顯示在屏幕上。
這兩個變量引用相同的 String 對象,但不是同一個對象。
6
String s = new String("Mom");
String s2 = new String("Mom");
System.out.println(s.equals(s2));
比較對象
true將顯示在屏幕上。
這兩個變量引用相同的 String 對象

“哦,我差點忘了!這裡有一些練習給你:”

4
任務
Java Syntax,  等級 4課堂 6
上鎖
Minimum of two numbers
All search and sort algorithms are based on comparisons. You'll be able to handle these very soon, if you so desire. In the meantime, we suggest starting with something small: write a program to find the minimum of two numbers. Find it and then display it. And if the numbers are the same, display either of them.
4
任務
Java Syntax,  等級 4課堂 6
上鎖
Maximum of four numbers
Finding the maximum is an n-ary operation (an operation on n numbers) that returns the largest of several numbers. Never mind. We have no need for such definitions at the secret CodeGym center. We're here to learn how to write code. In this task, you need to use the keyboard to enter four numbers. Then determine the largest of them and display it on the screen.
8
任務
Java Syntax,  等級 4課堂 6
上鎖
Sorting three numbers
Planet Linear Chaos is populated by isomorphs. They are believed to have invented sorting algorithms. Everything in their heads is extremely well-ordered. They only issue planetary visas to people who know at least 7 sorting algorithms. Let's take our first step toward Linear Chaos: Read three numbers from the keyboard, put them in descending order, and then display them on the screen.
4
任務
Java Syntax,  等級 4課堂 6
上鎖
Jen or Jen?
Jen, Company X's admin, learned how to pilot a space ship and flew away to another planet. People in Company X are good and sincere. It's just that they're scatterbrained and they mix up names. So they decided that the new administrator would also be called Jen. Let's help Company X find their Jen: write a program that checks the identity of two entered names.