Sorting a string in Java is a common task in programming, especially when you need to arrange characters alphabetically or check for anagrams. Since strings in Java are immutable, we must first convert them into a character array, sort them, and then convert them back into a string.
Example Code
import java.util.Arrays;
public class SortString {
public static void main(String[] args) {
String str = "sandip";
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sortedStr = new String(chars);
System.out.println("Sorted String: " + sortedStr);
}
}
Output
Sorted String: adinps
Key Points
- Use
Arrays.sort()
to arrange characters in ascending order. - Convert the string to lowercase before sorting for case-insensitive results.
- Works for any string, including those with numbers and symbols.
FAQs – Sort a String in Java
1. How do you sort string in Java alphabetically?
Convert the string to a char[]
array, use Arrays.sort()
to sort it, and then create a new string from the sorted array.
2. Can we sort a string directly in Java?
No. Strings in Java are immutable, so you cannot change them directly. You must convert them into a character array before sorting.
3. How do I sort a string in reverse order in Java?
After sorting with Arrays.sort()
, reverse the array using a loop or use Collections.reverseOrder()
with a list of characters.
4. How can I sort a string without considering case (case-insensitive)?
Convert the string to lowercase (or uppercase) before sorting to ensure case-insensitive results.
5. Does Arrays.sort()
sort by ASCII or alphabetical order?Arrays.sort()
sorts characters based on their Unicode values, which means uppercase letters come before lowercase letters.
Find More Content on Notes IOE, Happy Learning!!
Do follow us on Instagram and Facebook to get the latest updates!