Wednesday, September 13, 2023

How to calculate Maximum and minimum in Java? Beginner Tutorial

Today's programming exercise for a beginner is to write a Java program to take input from the user and find out the maximum and minimum numbers and print them into the console. The purpose of this article is to teach you how to get input from a user in Java and how to use java.lang.Math class to perform some mathematical operation e.g. max, min or average. You can use the Scanner class, added in Java 1.5 to read user input from the console. The scanner needs an InputStream to read data and because you are reading from the console, you can pass System.in, which is InputStream for Eclipse console or command prompt, depending upon what you are using. 

This class also helps you to convert user input into requiring data type e.g. if a user enters numbers then you must convert them into int data type and store them into int variables as shown in our example. You can use nextInt() method to read user input as Integer.

Similarly, you can use nextLine() to read user input as String. There are other methods available to read a float, double, or boolean from the command prompt. Once you got both the numbers, it just matters of using a relational operator less than and greater than to find smaller and larger numbers, as shown in the following example.

After that you can Math.max() to find the maximum of two numbers, it should be the same as your earlier result. Similarly, we will ask the User to enter the number again and will display a minimum of two.




How to find Maximum and Minimum Example in Java

Our example program has two parts. In the first part, we take input from a user, uses the if block and relational operator to find the maximum value, and further used the Math.max() method for the same purpose. 

In the second part of the program, we have asked the user to enter two more numbers and then we use less than the operator and if block to find smaller of two. 

After that, we have used Math.min() function to calculate the minimum number again. If your program is correct then both output should be same.

Finding maximum and minimum in Java with example




Java Program to calculate Maximum and Minimum of Numbers

Here is our sample Java program to calculate and print the maximum and minimum of two numbers entered by the user in the command prompt. You can run this program from Eclipse IDE by just copy pasting after creating a Java project and selecting it. 

Eclipse will automatically create a source file with the same name as the public class and put it right package. Alternatively, you can also run this program from the command prompt by following the steps given here.

import java.util.Scanner;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * Java program to calculate Maximum and minimum of two numbers
 *  entered by user in console.
 *
 * @author Javin Paul
 */
public class MaxMinExerciseInJava {

    public static void main(String args[]) throws InterruptedException {

        Scanner scnr = new Scanner(System.in);

        // Calculating Maximum two numbers in Java
        System.out.println("Please enter two numbers to find maximum of two");

        int a = scnr.nextInt();
        int b = scnr.nextInt();

        if (a > b) {
            System.out.printf("Between %d and %d, maximum is %d %n", a, b, a);
        } else {
            System.out.printf("Between %d and %d, maximum number is %d %n",
                 a, b, b);
        }

        int max = Math.max(a, b);
        System.out.printf("Maximum value of %d and %d using Math.max() is
                   %d %n", a, b, max);

        // Calculating Minimum between two numbers in Java
        System.out.println("Please enter two numbers to find minimum of two");

        int x = scnr.nextInt();
        int y = scnr.nextInt();

        if (x < y) {
            System.out.printf("Between %d and %d, Minimum Number is %d %n",
                        x, y, x);
        } else {
            System.out.printf("Between %d and %d, Minimum is %d %n",
                        x, y, y);
        }

        int min = Math.min(x, y);
        System.out.printf("Maximum value of %d and %d using Math.min() is
                    %d %n", x, y, min);
    }

}

Output
Please enter two numbers to find maximum of two
10
11
Between 10 and 11, maximum number is 11
Maximum value of 10 and 11 using Math.max() is 11
Please enter two numbers to find minimum of two
45
32
Between 45 and 32, Minimum is 32
Maximum value of 45 and 32 using Math.min() is 32


That's all about how to calculate maximum and minimum of two numbers in Java. In this tutorial, you have learned how to get input from the user, how to use a relational operator to compare two numbers, and how to use java.lang.Math class to perform common mathematical operations e.g. finding maximum and minimum of two numbers. 

Thanks for reading this article. If you like then please share it with your friends and colleagues. If you have any questions or feedback, please drop a note. If you have any questions or doubt then please let us know and I'll try to find an answer for you. Btw, what is your favorite coding exercise? prime number, palindrome or this one?

P. S. - If you have started learning Java in school or any training center, I suggest you keep a copy of Head First Java or Core Java Volume 1 by Cay S. Horstmann for your own reference, those are two great Java books for beginners.


7 comments:

  1. Write c++ program to read name, account number and balance amount in the account of 5 customers by using array of structures and then perform the following according to the user choice
    1-display the amount in their account
    2- withdrawal the amount from their account
    3- display the name, account number and balance of the customers

    ReplyDelete
  2. How can you calculate int min and int max by reading values from input.nextInt() without using Integer.Max_VALUE or Integer.MIN_VALUE; My output should be this.
    System.out.println("The smallest value entered was: " + min);
    System.out.println("The largest value entered was: " + max);
    System.out.println("The range of the values was: " + (max - min));
    System.out.println("The sum of values entered was: " + total);
    System.out.println("The number of values entered was: " + ((int)(counter-1)));
    System.out.println("The average of the values entered was: " + (double)total / (counter-1));
    My smallest value is always 0 because 0 is a sentinel to exit.
    Thank you.

    ReplyDelete
  3. what if you want to accept an undetermined number of values and find the min max of thoose?

    ReplyDelete


  4. public class Arithmeticmean {


    public static void main (String[] args){

    int sum=0;
    int elemNo=0;
    int currElem;
    double result;
    int newsum=0;
    Scanner sc=new Scanner (System.in);


    while (sc.hasNextInt()){


    currElem=sc.nextInt();
    sum=sum+currElem;
    elemNo=elemNo+1;

    if(currElem>10){


    newsum=newsum+currElem;

    }




    }
    if (elemNo==0){

    System.err.print("No data avaible\n");
    System.exit(1);


    }

    sc.close();
    result=(double) sum/elemNo;




    System.out.print("the sum of "+elemNo);
    System.out.print(" is "+result+"\n");
    System.out.println("sum :"+newsum);



    System.exit(0);

    }

    i also wanna take min and max values in this how can i add i now code has some problems but its n ot important

    ReplyDelete
  5. public static void main(String args[]) throws InterruptedException { Scanner scnr = new Scanner(System.in); // Calculating Maximum two numbers in Java System.out.println("Please enter two numbers to find maximum of two"); int a = scnr.nextInt(); int b = scnr.nextInt(); if (a > b) { System.out.printf("Between %d and %d, maximum is %d %n", a, b, a); } else { System.out.printf("Between %d and %d, maximum number is %d %n", a, b, b); } int max = Math.max(a, b); System.out.printf("Maximum value of %d and %d using Math.max() is %d %n", a, b, max); // Calculating Minimum between two numbers in Java System.out.println("Please enter two numbers to find minimum of two"); int x = scnr.nextInt(); int y = scnr.nextInt(); if (x < y) { System.out.printf("Between %d and %d, Minimum Number is %d %n", x, y, x); } else { System.out.printf("Between %d and %d, Minimum is %d %n", x, y, y); } int min = Math.min(x, y); System.out.printf("Maximum value of %d and %d using Math.min() is %d %n", x, y, min); } }

    Read more: https://www.java67.com/2015/07/java-program-to-calculate-maximum-and-minimum.html#ixzz6bXqahi1m

    ReplyDelete
  6. How can I understand well array

    ReplyDelete
    Replies
    1. Just start using them, I have also wrote a Java array 101 article which explains all important points about array in Java, you can read that article to improve your understanding of array in Java.

      Delete

Feel free to comment, ask questions if you have any doubt.