Connors
Connors

Reputation: 1

Whats wrong with the following code

Why isn't the following code working ?

String s = "fecbda";
Arrays.sort(s.toCharArray());
System.out.println(s);

Upvotes: 0

Views: 166

Answers (2)

MT0
MT0

Reputation: 167972

It does not work as s.toCharArray():

Returns: a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.

The operative part of the documentation is that it creates a new array (i.e. a copy of the characters in the string) and when you sort that array you do not sort the String.

You cannot sort the string as it is immutable but you can make a new string out of the sorted character array like this:

String s = "fecbda";
char[] c = s.toCharArray();
Array.sort( c );
String n = new String( c );

As an alternative method, you can do it in Java 8 using streams:

String s = "fecbda";

String n = s.chars()  // Convert to an IntStream of character codes
            .sorted() // Sort
            .mapToObj(i -> Character.toString((char) i)) // Convert to strings
            .collect(Collectors.joining()); // Concatenate the strings.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533510

Strings are immutable so you can't change them, and you shouldn't expect this to do anything.

What you might have intended is

String s = "fecbda"; 
char[] chars = s.toCharArray();
Arrays.sort(chars); 
String s2 = new String(chars);
System.out.println(s2);

Upvotes: 2

Related Questions