How do I convert string to char array?

Here we have a small class that convert a string literal into array, a character array.

package org.kodejava.example.lang;

public class StringToArrayExample {
    public static void main(String[] args) {
        // We have a string literal that contains the motto of this website.
        String literal = "Kode Java - Learn Java Programming by Examples";

        // Now we want to convert or divided it into a small array of char.
        // To do this we can simply used String.toCharArray() method. This
        // method splits the string into an array of characters.
        char[] temp = literal.toCharArray();

        // Here we just iterate the char array and print it to our console.
        for (int i = 0; i < temp.length; i++) {

How do I create a repeated sequence of character?

This example show you how to create a repeated sequence of characters. To do this we use the Arrays.fill() method. This method fills an array of char with a character.

package org.kodejava.example.util;

import java.util.Arrays;

public class RepeatCharacterExample {
    public static void main(String[] args) {
        char c = 'x';
        int length = 10;

        // creates char array with 10 elements
        char[] chars = new char[length];

        // fill each element of chars array with 'x'
        Arrays.fill(chars, c);

        // print out the repeated 'x'

As the result you get the x character repeated 10 times.


For one liner code you can use the following code snippet, which will give you the same result.

new String(new char[10]).replace('\0', 'x');


String.join("", Collections.nCopies(10, "x"));