I'm new to Java, and I wrote code that sorts numbers, but I was trying to convert it to sort strings and it won't work. What is the most basic way of sorting strings in alphabetical order?
2 Answers
Simply do it as below:
Arrays.sort(name);
2 Comments
KidKool
Where/how would I initialize Arrays.sort()?
Bahramdun Adil
Arrays is a Util class in Java, Just import it and you can use its methods. No need to init that, all methods are in staticJava Strings are Comparables, meaning they have a compareTo method which can be used to compare two such objects. a.compareTo(b) will return a negative value if a is logically less than b, a positive value if a is greater than b or 0 if they are equal.
So you can keep your entire logical flow and just change the comparison check - instead of if (name[y] > name[y+1] ) you'd need to use if (name[y].compareTo(name[y+1]) > 0 ).
1 Comment
KidKool
Thank you. You just solved all my problems. Thanks for explaining and hat link to the old question was very helpful too.
Arrays.sort().Xwill come beforea