English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java Math mathematical methods
La méthode Java Math max() retourne la valeur maximale des paramètres spécifiés.
La syntaxe de la méthode max() est :
Math.max(arg1, arg2)
Attention:max() est une méthode statique. Par conséquent, nous pouvons utiliser le nom de la classe Math pour accéder à cette méthode.
arg1 / arg2 - Paramètres pour retourner la valeur maximale
Remarque:Les types de données des paramètres doivent être int, long, float ou double.
Retourne la valeur maximale des paramètres spécifiés
class Main { public static void main(String[] args) { //Math.max() avec un paramètre int int num1 = 35; int num2 = 88; System.out.println(Math.max(num1, num2)); // 88 //Math.max() avec un paramètre long long num3 = 64532L; long num4 = 252324L; System.out.println(Math.max(num3, num4)); // 252324 //Math.max() avec un paramètre float float num5 = 4.5f; float num6 = 9.67f; System.out.println(Math.max(num5, num6)); // 9.67 //Math.max() avec un paramètre double double num7 = 23.44d; double num8 = 32.11d; System.out.println(Math.max(num7, num8)); // 32.11 } }
Dans cet exemple, nous utilisons la méthode Math.max() avec les paramètres de type int, long, float et Double.
class Main { public static void main(String[] args) { //Créer un tableau de type int int[] arr = {4, 2, 5, 3, 6}; //Définir le premier élément de l'array comme la valeur maximale maximale int max = arr[0]; for (int i = 1; i < arr.length; i++) { //Compare all elements with max //Assign the maximum value to max max = Math.max(max, arr[i]); } System.out.println("Maximum value: " + max); } }
In the above example, we created an array named arrArray. Initially, the variable max stores the first element of the array.
Here, we use a for loop to access all elements of the array. Note this line,
max = Math.max(max, arr[i])
The Math.max() method compares the variable max with all elements of the array and assigns the maximum value to max.