Java Math: Comparing Numbers
There will be occasions when it will be necessary for your program to determine which of two number is the larger and which is the smaller. For example your program may be a banking application and it way need to determine which account has the most money in it, or it may be a product itinerary application and it may need to determine which category of product has the fewest products listed.
The min() method requires two numbers (let’s call them x and y) to compare and will return the smaller of the two. The general syntax is:
Math.min(x,y);
Let’s see how we might return the smaller of two numbers in code by comparing two numbers and then comparing the values of two variables in Java:
//compare two numbers System.out.println(Math.min(200,300)); //compare two variable values int x = 250, y = 350; System.out.println(Math.min(x,y));
The output should be the higher of the two combinations:
run: 200 250 BUILD SUCCESSFUL (total time: 0 seconds)
The max() method also requires two numbers (again let’s call them x and y) to compare and will return the larger of the two. The general syntax is:
Math.max(x,y);
Let’s see how we might return the larger of two numbers in code by comparing two numbers and then comparing the values of two variables in Java:
//compare two numbers System.out.println(Math.max(200,300)); //compare two variable values int x = 250, y = 350; System.out.println(Math.max(x,y));
The output should be the higher of the two combinations:
run: 300 350 BUILD SUCCESSFUL (total time: 0 seconds)