TechTorch

Location:HOME > Technology > content

Technology

Sorting Arrays in Java: A Comprehensive Guide for String and Numeric Arrays

June 16, 2025Technology3160
Sorting Arrays in Java: A Comprehensive Guide for String and Numeric A

Sorting Arrays in Java: A Comprehensive Guide for String and Numeric Arrays

When working with arrays in Java, one of the most common tasks is sorting the elements in a specific order. Whether you are dealing with a string array or a numeric array, Java provides a straightforward and efficient way to perform this operation. This article will guide you through the steps required to sort both types of arrays in Java.

Sorting a Numeric Array in Java

Sorting a numeric array in Java can be achieved using the () method. This built-in utility sorts the array elements in ascending order by default. Additionally, you can sort the array in descending order using the (array, ()) method.

Code Example: Sorting an Integer Array

public class SortArrayApp {
tpublic static void main(String[] args) {
ttint[] arr  {34, 12, 27, 9, 56, 3, 16};
tt
tt// Ascending order
(arr);
("Ascending order: "   (arr));
tt
tt// Descending order
(arr, ());
("Descending order: "   (arr));
t}
}

The output of the above code will be:

Ascending order: [3, 9, 12, 16, 27, 34, 56] Descending order: [56, 34, 27, 16, 12, 9, 3]

To ensure the quality of your code, it's important to import the necessary classes:

import ;
import ;

Sorting a String Array in Java

Sorting a string array in Java is similar to sorting a numeric array. The () method is used to sort the array elements alphabetically by default. If you need to sort the strings in a specific order (e.g., descending), you can use the (array, _INSENSITIVE_ORDER) method for case-insensitive ordering or a custom comparator.

Code Example: Sorting a String Array

public class StringSortExample {
tpublic static void main(String[] args) {
ttString[] arr  {"orange", "apple", "banana", "cherry", "date"};
tt
tt// Case-sensitive sorting
(arr);
("Sorted array: "   (arr));
tt
tt// Case-insensitive sorting
(arr, _INSENSITIVE_ORDER);
("Case-insensitive sorted array: "   (arr));
t}
}

The output of the above code will be:

Sorted array: [apple, banana, cherry, date, orange] Case-insensitive sorted array: [apple, banana, cherry, date, orange]

Conclusion

In the above examples, we demonstrated how to sort both numeric and string arrays in Java. By using the built-in () method and its variations, you can easily sort your arrays in the desired order. Remember to import the necessary classes to use these methods effectively.