Practical Examples of Integer Comparison
Now that you have a solid understanding of integer comparison in Java, let's explore some practical examples to solidify your knowledge.
Comparing Integers in Conditional Statements
One of the most common use cases for integer comparison is in conditional statements, such as if-else
and switch-case
. These statements allow you to execute different blocks of code based on the result of the comparison.
int age = 25;
if (age < 18) {
System.out.println("You are a minor");
} else if (age >= 18 && age < 65) {
System.out.println("You are an adult");
} else {
System.out.println("You are a senior");
}
In this example, the program will output "You are an adult" because the age
variable is 25, which falls within the range of 18 to 65.
Sorting Integers
Integer comparison is also essential for sorting algorithms, such as bubble sort, merge sort, and quicksort. These algorithms rely on comparing integers to determine the correct order of the elements in an array.
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 5, 8, 9]
In this example, the Arrays.sort()
method uses integer comparison to sort the numbers
array in ascending order.
Finding the Minimum and Maximum Values
Comparing integers is also useful for finding the minimum and maximum values in a set of numbers.
int a = 10;
int b = 20;
int c = 5;
int min = Math.min(a, Math.min(b, c));
int max = Math.max(a, Math.max(b, c));
System.out.println("Minimum value: " + min); // Output: Minimum value: 5
System.out.println("Maximum value: " + max); // Output: Maximum value: 20
In this example, the Math.min()
and Math.max()
methods are used to find the minimum and maximum values among the three integers a
, b
, and c
.
By exploring these practical examples, you can see how integer comparison is a fundamental operation in Java that can be applied to a wide range of programming tasks, from decision-making to data manipulation and sorting.