-3

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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
KidKool
  • 43
  • 4

2 Answers2

1

Simply do it as below:

Arrays.sort(name);
Bahramdun Adil
  • 5,772
  • 6
  • 34
  • 63
0

Java 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 ).

Mureinik
  • 277,661
  • 50
  • 283
  • 320
  • 1
    Thank 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