-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?

3
  • You must know about how to compare strings in java. Commented Feb 17, 2016 at 6:49
  • What about Arrays.sort(). Commented Feb 17, 2016 at 6:49
  • 1
    @Satya - Wont work.. It sorts in Natural order, X will come before a Commented Feb 17, 2016 at 6:50

2 Answers 2

1

Simply do it as below:

Arrays.sort(name);
Sign up to request clarification or add additional context in comments.

2 Comments

Where/how would I initialize Arrays.sort()?
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
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 ).

1 Comment

Thank you. You just solved all my problems. Thanks for explaining and hat link to the old question was very helpful too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.