JavaDevNotes.com

Java Char Array

When we are dealing with a handful of data of the same type, we can use a different variable for each. But if we are working with arbitrarily more numbers of data of same type, array can be a good choice because it is a simple data structure to work with. List or Set is also a good choice, but arrays is much simpler to manipulate and work with. We explore below how do we work with Java Char Array. We will check different common scenario we encounter when working with char arrays.

Java Char Array Declaration

Declaring a variable to be a char array is straightforward and simple in Java. We can use the square brackets to do this. For example:

char[] thisIsACharArray;

The square brackets is placed right after the word char and before the variable name. Arbitrarily, we can also put the square brackets at the end of the variable name like shown below.
char thisIsACharArray[];
Both ways are perfectly fine way of declaring a Java Char Array.

Java Char Array Declaration With Instance And Initial Size

When we work with arrays, we typically assign an instance right away with a default size. For example:
char[] thisIsACharArray = new char[5];
This declares a Java Char Array and assign an instance with size 5. Each item of the char array, being of primitive type, contains the char equivalent of the byte value 0. We can also add code to assign values after our declaration, for example:
char[] thisIsACharArray = new char[5];
thisIsACharArray[0] = 'a';
thisIsACharArray[1] = 'b';
thisIsACharArray[2] = 'c';
thisIsACharArray[3] = 'd';
thisIsACharArray[4] = 'e';

Java Char Array Declaration With Instance And Values

Sometimes we already know beforehand what is the initial contents of our array. For this case, we can declare our Java Char Array variable and assign an instance with values already. Sample code is shown below:
char[] thisIsACharArray = {'a', 'z', 'c', 'm', 'x'};
This declares a Java Char Array with instance of size 5. The first element is a, the second element is z, the third element is c, the fourth is m, and the last one is x.

Java Char Array Declaration Initialize After Declaration

For the scenario where we don't know beforehand the size and contents of our array, but we want to declare it anyways. And then we will know at later point what is the initial content, we can initialize the contents of an array later. Below is an example:
char[] thisIsACharArray;
...
thisIsACharArray = new char[] {'a', 'z', 'c', 'm', 'x'};
The three dots just means there might be some code in between the two lines, meaning something happens before we could initialize our Java Char Array. Of course the code below may also work:
char[] thisIsACharArray;
...
thisIsACharArray = new char[5];
thisIsACharArray[0] = 'a';
thisIsACharArray[1] = 'z';
thisIsACharArray[2] = 'c';
thisIsACharArray[3] = 'm';
thisIsACharArray[4] = 'x';

Java Char Array Loop Values

A common scenario we encounter is we sometimes need to loop through and visit each value in our array. We can use the Java 5 for loop for this case as shown below:
char[] thisIsACharArray = {'a', 'z', 'c', 'm', 'x'};
for (char c:thisIsACharArray) {
    System.out.println(c);
}
That will output like below:
a
z
c
m
x
If we do not like this shortcut way of loop, we can do a longer version using below:
char[] thisIsACharArray = {'a', 'z', 'c', 'm', 'x'};
for (int i=0; i<thisIsACharArray.length; i++) {
    System.out.println(thisIsACharArray[i]);
}
Which will result with the same output.

Java Char Array Size or Length

This was actually shown in previous example, but below is a sample way if we want to know the length of an existing char array.

char[] thisIsACharArray = {'a', 'z', 'c', 'm', 'x'};
System.out.println(thisIsACharArray.length);

This will output 5 as this is the number of items in the array.
5

Java Char Array Sorting

Another common use case when working with arrays is if we want to sort the elements. This is easy to do as Java provides a utility out of the box. We can use Arrays.sort() for this as shown below:

char[] thisIsACharArray = {'a', 'z', 'c', 'm', 'x'};
Arrays.sort(thisIsACharArray);
System.out.println(Arrays.toString(thisIsACharArray));

The output is the contents of the array in sorted order.
[a, c, m, x, z]
If we want to be more adventurous, we can just write our own sorting implementation.
public class Test {
    public static void main(String[] args) {
        char[] thisIsACharArray = { 'a', 'z', 'c', 'm', 'x' };
        int j = 0;
        char tmp;
        boolean sorted = false;
        while (!sorted) {
            sorted = true;
            j++;
            for (int i = 0; i < thisIsACharArray.length - j; i++) {
                if (thisIsACharArray[i] > thisIsACharArray[i + 1]) {
                    tmp = thisIsACharArray[i];
                    thisIsACharArray[i] = thisIsACharArray[i + 1];
                    thisIsACharArray[i + 1] = tmp;
                    sorted = false;
                }
            }
        }
        System.out.println(Arrays.toString(thisIsACharArray));
    }
}
The code above will sort and output the expected ordered result.

Java Char Array To List Conversion

Sometimes when array is not enough, we may want to convert our Java Char Array to a List. Below is a way to do that:

package mytest;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
public class Test {
    public static void main(String[] args) {
        char[] thisIsACharArray = { 'a', 'z', 'c', 'm', 'x' };
        Character[] thisIsACharacterArray = ArrayUtils.toObject(thisIsACharArray);
        List<Character> characterList = Arrays.asList(thisIsACharacterArray);
        System.out.println(characterList.toString());
    }
}

As shown above, we first need to convert char[] to Character[]. This is because we can't create a List of char as Collections api requires Object and not primitives. For that we used apache common's ArrayUtils.
Character[] thisIsACharacterArray = ArrayUtils.toObject(thisIsACharArray);
And then we converted it to List of Character.
List<Character> characterList = Arrays.asList(thisIsACharacterArray);