Opérateurs de comparaison

Introduction à Java

Jim White

Java Developer

Comparaisons

 

 

  • Évaluez toujours sur true ou false (le résultat est boolean)

Comparaison de l'âge avec minAge

Introduction à Java

Supérieur à >, inférieur à <

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

Supérieur à >, inférieur à <

// 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
Introduction à Java

Supérieur ou égal à >=

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
Introduction à Java

Inférieur ou égal à <=

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
Introduction à Java

Égal ==

  • Nous devons utiliser ==, = est destiné aux assignations
int userAccountNumber = 567346;
int submittedAccountNumber = 456777;

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

Introduction à Java

Inégal !=

  • Utilisez !=.
int userHealth = 235;

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

Résumé comparatif

Opérateur Nom Exemple Résultat de l'exemple
> Supérieur à 6 > 6 false
< Inférieur à 5 < 6 true
>= Supérieur ou égal à 5 >= 6 false
<= Inférieur ou égal à 5 <=6 true
== Égal à 5 == 5 true
!= N'est pas égal à 5 != 5 false
  • La sortie de toutes les opérations est un boolean
Introduction à Java

Passons à la pratique !

Introduction à Java

Preparing Video For Download...