logo

Metodo Java Integer compare()

IL confrontare() il metodo è un metodo di Classe intera Sotto pacchetto java.lang . Questo metodo confronta numericamente due valori interi. Restituisce il risultato in valore intero equivalente confrontando il metodo due int argomenti . Il valore restituito è identico a quello che verrebbe restituito da:

Integer.valueOf(x).compareTo(Integer.valueOf(y))

Sintassi

Di seguito la dichiarazione di confrontare() metodo:

 public static int compare(int x,int y) 

Parametro:

Tipo di dati Parametro Descrizione Obbligatorio/facoltativo
int X Il primo valore intero da confrontare Necessario
int E Il secondo valore intero da confrontare Necessario

Ritorna:

Questo metodo restituirà i seguenti valori:

 0 = The value 0 if x == y, -1 = The value less than 0 if x y 

Eccezioni:

QUELLO

Versione compatibile:

Java 1.7 e versioni successive

Esempio 1

 public class IntegerCompareExample1 { public static void main(String[] args) { int num1 = 10; int num2 = 20; int num3 = 10; int num4 = 30; // as num1 less than num2, Output will be less than zero System.out.println(Integer.compare(num1, num2)); // as num1 equals num3, Output will be zero System.out.println(Integer.compare(num1, num3)); // as num4 is greater than num2, Output will be greater than zero System.out.println(Integer.compare(num4, num2)); } } 
Provalo adesso

Produzione:

 -1 0 1 

Esempio 2

 import java.util.Scanner; public class IntegerCompareExample2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print(&apos;Enter the first numeric value: &apos;); int number1 = sc.nextInt(); System.out.print(&apos;Enter the second numeric value: &apos;); int number2 = sc.nextInt(); sc.close(); // compares two Integer values numerically int retResult = Integer.compare(number1, number2); if(retResult &gt; 0) { System.out.println(&apos;number1 is greater than number2&apos;); } else if(retResult<0) { system.out.println('number1 is less than number2'); } else equal to < pre> <p> <strong>Output:</strong> </p> <pre> Enter the first numeric value: 55 Enter the second numeric value: 66 number1 is less than number2 </pre> <h2>Example 3</h2> <pre> public class IntegerCompareExample3 { public static void main(String[] args) { System.out.println(Integer.compare(200, 100)); System.out.println(Integer.compare(200, 200)); System.out.println(Integer.compare(100, 150)); } } </pre> <span> Test it Now </span> <p> <strong>Output:</strong> </p> <pre> 1 0 -1 </pre> <br></0)>

Esempio 3

 public class IntegerCompareExample3 { public static void main(String[] args) { System.out.println(Integer.compare(200, 100)); System.out.println(Integer.compare(200, 200)); System.out.println(Integer.compare(100, 150)); } } 
Provalo adesso

Produzione:

 1 0 -1