Jämförelseoperatorer

Introduktion till Java

Jim White

Java Developer

Jämförelser

 

 

  • Utvärderas alltid till true eller false (resultatet är ett boolean)

Jämför age med minAge

Introduktion till Java

Större än >, mindre än <

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

Större än >, mindre än <

// 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
Introduktion till Java

Större än eller lika med >=

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
Introduktion till Java

Mindre än eller lika med <=

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
Introduktion till Java

Lika med ==

  • Använd ==; = används för tilldelning
int userAccountNumber = 567346;
int submittedAccountNumber = 456777;

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

Introduktion till Java

Inte lika med !=

  • Använd !=
int userHealth = 235;

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

Sammanfattning av jämförelseoperatorer

Operator Namn Exempel Resultat
> Större än 6 > 6 false
< Mindre än 5 < 6 true
>= Större än eller lika med 5 >= 6 false
<= Mindre än eller lika med 5 <=6 true
== Lika med 5 == 5 true
!= Inte lika med 5 != 5 false
  • Alla operationer returnerar ett boolean
Introduktion till Java

Nu kör vi en övning!

Introduktion till Java

Preparing Video For Download...