比較運算子

Java 入門

Jim White

Java Developer

比較

 

 

  • 總是評估為 truefalse(結果為 boolean

將 age 與 minAge 比較

Java 入門

大於 >、小於 <

class GreaterThan {
  public static void main(String[] args){
    System.out.println(5 < 6); // Will print true, 5 is less than 6
  }
}
true
Java 入門

大於 >、小於 <

// Check if 5 is less than 6
boolean x = 5 < 6; // Value is true, because 5 < 6

// Check if 5 is greater than 6
boolean y = 5 > 6; // Value is false, 5 < 6
Java 入門

大於等於 >=

int minSpend = 25;
int total = 25;


// Check if total is greater or equal to minSpend boolean freeDelivery = total >= minSpend; // Value is true, total is equal to minSpend
Java 入門

小於等於 <=

int minSpend = 25;
int total = 23;

// Check if total is less or equal to minSpend

boolean paidDelivery = total <= minSpend; // Value is true, total is less than minSpend
Java 入門

等於 ==

  • 需要用 === 是指定運算子
int userAccountNumber = 567346;
int submittedAccountNumber = 456777;

// Check if userAccountNumber is equal to submittedAccountNumber
boolean isUserAccountNumber = useraccountNumber == submittedAccountNumber;
// Value is false

Java 入門

不等於 !=

  • 使用 !=
int userHealth = 235;

// Check whether userHealth is not zero
boolean alive = userHealth != 0; // Value is true, userHealth is not zero
Java 入門

比較總結

運算子 名稱 範例 範例結果
> 大於 6 > 6 false
< 小於 5 < 6 true
>= 大於等於 5 >= 6 false
<= 小於等於 5 <=6 true
== 等於 5 == 5 true
!= 不等於 5 != 5 false
  • 所有運算的輸出都是 boolean
Java 入門

一起來練習吧!

Java 入門

Preparing Video For Download...