0

Why isn't the following code working ?

String s = "fecbda";
Arrays.sort(s.toCharArray());
System.out.println(s);
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
Connors
  • 1
  • 2
  • http://stackoverflow.com/q/36510808/3973077 – Paul Boddington Apr 09 '16 at 22:50
  • 1
    What is wrong about it? please use a proper title for your question (more specific than that) – Sevle Apr 09 '16 at 22:51
  • 2
    "*Questions seeking debugging help ("why isn't this code working?") must **include the desired behavior, a specific problem or error** and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.*" - [What topics can I ask about here?](http://stackoverflow.com/help/on-topic) – Vince Apr 09 '16 at 22:57

2 Answers2

2

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);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • You can print `chars` directly. No need to create `s2`. – Andreas Apr 09 '16 at 23:01
  • 1
    For a complete answer, quote javadoc of [`toCharArray()`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray%28%29): *Returns a **newly allocated** character array* – Andreas Apr 09 '16 at 23:04
  • @Andreas You can't use `System.out.println(chars)` but you can do `System.out.println(Arrays.toString(chars))` which I suspect is not what the OP expected. – Peter Lawrey Apr 09 '16 at 23:06
  • 1
    Yeah you can. See [`PrintStream.println(char[])`](https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println%28char[]%29) – Andreas Apr 09 '16 at 23:08
1

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.
MT0
  • 143,790
  • 11
  • 59
  • 117