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?
Asked
Active
Viewed 115 times
-3
-
You must know about how to compare strings in java. – SatyaTNV Feb 17 '16 at 06:49
-
What about `Arrays.sort()`. – SatyaTNV Feb 17 '16 at 06:49
-
1@Satya - Wont work.. It sorts in Natural order, `X` will come before `a` – TheLostMind Feb 17 '16 at 06:50
2 Answers
1
Simply do it as below:
Arrays.sort(name);

Bahramdun Adil
- 5,907
- 7
- 35
- 68
-
-
`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 `static` – Bahramdun Adil Feb 17 '16 at 06:54
0
Java String
s are Comparable
s, 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 )
.

Mureinik
- 297,002
- 52
- 306
- 350
-
1Thank you. You just solved all my problems. Thanks for explaining and hat link to the old question was very helpful too. – KidKool Feb 17 '16 at 06:58