dev
dev

Reputation: 137

void error in Arrays.sort() in java

String text1 = "check";

char c[] = Arrays.sort(text1.toCharArray());

Output:

error: incompatible types

    char c[] = Arrays.sort(text1.toCharArray());
    required: char[]
    found:    void
    1 error

Why does it not work that way?

Upvotes: 2

Views: 11074

Answers (4)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

The Arrays.sort() method has a return type of void, meaning it does not return an object/primitive, so you can't really assign the absent return value to a char[]. The array will be sorted through the reference to it (arrays are objects) passed to the method.

BTW, the same applies for Collections.sort()

See the documentation

FIX

String text1 = "check";
char c[] = text.toCharArray();
Arrays.sort(c);

Upvotes: 13

Mengjun
Mengjun

Reputation: 3197

Note that Arrays.sort does not return type.

Source code is as follows:

public static void sort(char[] a) {
    DualPivotQuicksort.sort(a);
}

If you want to sort the char array You can use the following way:

    String text1 = "hello";
    char c[] = text1.toCharArray();

    //Sort char array
    Arrays.sort(c);

    //Print [e,h,l,l,o]
    System.out.println(Arrays.toString(c));

Upvotes: 3

Aniket Thakur
Aniket Thakur

Reputation: 68915

Arrays.sort(); returns void you cannot assign it to an char array i.e char[]

Upvotes: 3

ile
ile

Reputation: 349

Arrays.sort() returns void not char[]

Upvotes: 2

Related Questions