You need to read more about Reading from input streams. You can start here, but there are other wonderful tutorials out there.

Not exactly answering your question (because it's still ambiguous), but in the following I've read 5 characters from input and output the sorted character array. This will help you get started.

public static void main(String[] args) throws IOException {

        char arr[] = new char[5];
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter input characters and press enter: "); 
        for(int i=0; i<arr.length; i++) {
            arr[i] = (char) br.read();
        }       
        br.close();
        Arrays.sort(arr);
            System.out.println("Sorted Array: "+String.valueOf(arr));   
    }

Console I/O:

Enter input characters and press enter:
zeros
Sorted Array: eorsz

Further as Rohit has already mentioned you should look up the String class and its extensive utilities functions. Also, as you also mention that you don't probably know the number of elements in your array, you might want to look at it as a List, in which case you should use List<Character>.

Answer from zEro on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › character-array-in-java
Character Array in Java - GeeksforGeeks
January 22, 2026 - A character array in Java is an array that stores multiple characters (char) in contiguous memory locations.
Discussions

how to add char values to char array in java - Stack Overflow
I'm trying to put the complement results from a char into a char array complement1. I thought I can use the operator but that's only for strings but I'm having a hard time trying to figure out how... More on stackoverflow.com
🌐 stackoverflow.com
appending char to char array java - Stack Overflow
I'm trying to write a method that takes in and a returns a character array. I want to replace every space ' ' with 'h''i'. I can't use the string class or any other helper classes. I'm getting s... More on stackoverflow.com
🌐 stackoverflow.com
Add Something to Char Array at Specific Spot (Java) - Stack Overflow
I am tasked with taking a user sentence then separating it at the upper case letters as well as making those letters lower case after adding a " ". I want to add a space add that position... More on stackoverflow.com
🌐 stackoverflow.com
Adding Char to Char Array in Java - Stack Overflow
I'm still pretty new to Java so bear with me. I'm making a simple hangman game that takes input from the user. I am trying to append the guessed letter to the knownLetters array but I get a type mi... More on stackoverflow.com
🌐 stackoverflow.com
🌐
CodingTechRoom
codingtechroom.com › question › how-to-append-to-char-array-in-java
How to Append to a char[] Array in Java - CodingTechRoom
However, there are a few effective methods to achieve this functionality by creating a new array and copying the existing elements along with the new ones. ... public static char[] appendToCharArray(char[] array, char newChar) { char[] newArray = new char[array.length + 1]; System.arraycopy(array, ...
🌐
Stack Overflow
stackoverflow.com › questions › 64541296 › how-to-add-char-values-to-char-array-in-java
how to add char values to char array in java - Stack Overflow
I'm trying to put the complement results from a char into a char array complement1. I thought I can use the operator but that's only for strings but I'm having a hard time trying to figure out how...
🌐
TutorialsPoint
tutorialspoint.com › article › different-methods-to-append-a-single-character-to-a-string-or-char-array-in-java
Different methods to append a single character to a string or char array in Java
August 25, 2022 - You can choose the best way by analyzing the output you desire for. The two methods are, ... System.arraycopy() method. ... Generally, a string is immutable, i.e., the sequence data of the string cannot be changed.
Top answer
1 of 1
2

Your fundamental problem seems to be that you don't seem to understand how arrays work in Java.

In Java, arrays have a fixed length, and each location can hold only one of the declared data type. So for instance, if you have this char[]: [w, h, a, t, s, , u, p], its length will permanently be fixed at 8.

You can replace the character in a given location, but if you do that more than once, you will just overwrite the value.

    char[] characterStr = {'w','h','a','t','s',' ','u','p'};
    characterStr[5] = 'h'; // [w, h, a, t, s, h, u, p]
    characterStr[5] = 'i'; // [w, h, a, t, s, i, u, p]

Also, you cannot use += to try to append a value:

    char[] characterStr = {'w','h','a','t','s',' ','u','p'};
    characterStr += 'h'; // compile error! operator += is undefined for these arguments

You have to assign a value to a given location, using the arrayname[index] = value; syntax.

What you need to do (as mentioned in the comments), is first calculate the size of the array you are trying to create, by counting the number of spaces in the original array. You are already looping through and looking for spaces, so you just need to replace the code where you try to modify the array with a count, and create the output array based on that size:

    int size = input.length;
    for (char ch: input) {
        if (ch == ' ') {
            size += 1;
        }
    }
    char[] total = new char[size];

Also note that I didn't just declare total as a variable of type char[], but I used the new keyword to actually create it. Like other objects, arrays in Java need to be explicitly created, or you will end up with a NullPointerException when you try to use it.

Once you have created your new array, you can loop through your original input array and copy the non-space characters over (or 'h' and 'i' when you see a space).

You won't want to use a for-each loop for this, since you'll need to manually keep track of the array indices. (Hint: the index into the input array and the index into the output array won't be the same once you see a space).

Find elsewhere
🌐
Huda Tutorials
hudatutorials.com › java › basics › java-arrays › java-char-array
Java char Array - char array in java - Huda Tutorials
July 16, 2021 - If you try to store long (big) elements in array, you will get performance problems. If you overcome performance problems you should go to java collections framework or simply use Vector. ... /* Java char Array Example Save with file name CharArray.java */ public class CharArray { public static void main(String args[]) { // JAVA CHAR ARRAY DECLARATION char c[]; // MEMORY ALLOCATION FOR JAVA CHAR ARRAY c = new char[4]; // ASSIGNING ELEMENTS TO JAVA CHAR ARRAY c[0] = 'a'; c[1] = 'c'; c[2] = 'D'; c[3] = 'B'; // JAVA CHAR ARRAY OUTPUT System.out.println("Java char Array Example"); for(int i=0;i<c.length;i++) { System.out.println("Element at Index : "+ i + " " + c[i]); } } }
🌐
Dot Net Perls
dotnetperls.com › char-array-java
Java - char Array - Dot Net Perls
January 25, 2024 - In Java, Strings are immutable: they cannot be changed in place or added to. With char arrays, we manipulate character buffers. Char arrays are faster—we can change text data without allocations. With the String constructor, we can convert back into a string. To begin, char arrays support the array initializer syntax like other arrays. Here we create a new array with 3 elements...
Top answer
1 of 3
1

There is no add method for arrays. Arrays are not resizeable. If you indeed want to use a char[] array, you need to allocate one that is large enough, e.g. by counting the uppercase letters or simply by allocating a array that is surely large enough (twice the String length minus 1).

String input = ...

String outputString;

if (input.isEmpty()) {
    outputString = "";
} else {
    char[] output = new char[input.length() * 2 - 1];
    output[0] = input.charAt(0);
    int outputIndex = 1;
    for (int i = 1; i < input.length(); i++, outputIndex++) {
        char c = input.charAt(i);
        if (Character.isUpperCase(c)) {
            output[outputIndex++] = ' ';
            output[outputIndex] = Character.toLowerCase(c);
        } else {
            output[outputIndex] = c;
        }
    }
    outputString = new String(output, 0, outputIndex);
}

System.out.println(outputString);

Or better still use a StringBuilder

String input = ...

String outputString;

if (input.isEmpty()) {
    outputString = "";
} else {
    StringBuilder sb = new StringBuilder().append(input.charAt(0));

    for (int i = 1; i < input.length(); i++) {
        char c = input.charAt(i);
        if (Character.isUpperCase(c)) {
            sb.append(' ').append(Character.toLowerCase(c));
        } else {
            sb.append(c);
        }
    }
    outputString = sb.toString();
}

System.out.println(outputString);
2 of 3
0

You're approaching this the wrong way. Just add each char back to a new string but with spaces included at the right spots. Don't worry about modifying your char array at all. Here is a slight modification of your code:

  public static void main(String[] args)
  {
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter a sentence");
    String sentenceString = s.nextLine();
    char[] sentenceArray = sentenceString.toCharArray();

    //new string to hold the output
    //starts with only the first char of the old string
    string spacedString = sentenceArray[0] + "";

    for(int i = 1; i < sentenceArray.length; i++)
    {
      if(Character.isUpperCase(sentenceArray[i]))
      {
        //if we find an upper case char, add a space and the lower case of that char
        spacedString = spacedString + " " + Character.toLowerCase(sentenceArray[i]);    
      }else {
        //otherwise just add the char itself
        spacedString = spacedString + sentenceArray[i];
      }
    }

    System.out.println(spacedString)
    s.close();
  }

If you want to optimize performance, you can use a StringBuilder object. However, for spacing out a single sentence, performance isn't going to make any real difference at all. If performance does matter to you, read more on StringBuilder here: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

🌐
Java2s
java2s.com › ref › java › java-array-append-a-char-to-char-array.html
Java Array append a char to char array
* * @param c The chars to where the new char should be appended * @param toAdd the char to be added * @return a new array with the passed char appended. */ public static char[] addChar(char[] c, char toAdd) { char[] c1 = new char[c.length + 1]; System.arraycopy(c, 0, c1, 0, c.length); c1[c.length] = toAdd; return c1; } } PreviousNext · Java Array multidimensional Arrays reference element ·
🌐
Medium
mvthanoshan.medium.com › string-to-char-array-java-tutorial-4925e1912cc3
String to Char Array Java Tutorial | by Thanoshan MV | Medium
May 7, 2021 - Length is vowels' length char[] vowelArray = new char[vowels.length()];// loop to iterate each characters in the 'vowels' string for (int i = 0; i < vowels.length(); i++) { // add each character to the character array vowelArray[i] = vowels.charAt(i); }// print the array System.out.println(Arrays.toString(vowelArray)); ... You can read more about the charAt() instance method in the Java documentation.
🌐
Tutorialspoint
tutorialspoint.com › java › io › chararraywriter_append.htm
Java - CharArrayWriter append(char c) method
August 25, 2022 - package com.tutorialspoint; import java.io.CharArrayWriter; public class CharArrayWriterDemo { public static void main(String[] args) { CharArrayWriter chw = null; // create buffer char[] ch = {'A','B','C','D','E','F'}; try { // create new character array writer chw = new CharArrayWriter(); // for each character in the buffer for(char c:ch) { // append character to the writer chw.append(c); // prints the character array as string System.out.println(chw.toString()); } } catch(Exception e) { // for any exception e.printStackTrace(); } finally { // closes the stream if(chw!=null) chw.close(); } } }
🌐
Edureka Community
edureka.co › home › community › categories › java › how can i add new elements to an array in java
How can I add new elements to an Array in Java | Edureka Community
April 19, 2018 - I want to append elements to an array String[] mm= {"5","4","3"}; mm.append("2"); This ... give me a way in which I can add elements to this array.
🌐
javaspring
javaspring.net › blog › how-to-add-to-an-array-in-java
How to Add Elements to an Array in Java — javaspring.net
Arrays are a fundamental data structure in Java, used to store multiple values of the same type in a contiguous memory location. However, Java arrays have a fixed size, which means that once an array is created, its size cannot be changed. This presents a challenge when you need to add new elements to an existing array.
🌐
Upgrad
upgrad.com › home › blog › software development › complete guide to char in java: declaration, size, common use cases and more
Exploring Char in Java: Size, Declaration, and Applications
July 7, 2026 - Set the loop condition to continue until i reaches the length of the array. Increment i after each iteration to move to the next element. ... Imagine you are storing the first letters of some famous Indian festivals. This example demonstrates how to use the regular for loop in Java to print each festival's initial letter. char[] festivalSymbols = {'D', 'R', 'H', 'D', 'G'}; // D for Diwali, R for Raksha Bandhan, etc.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › stringbuilder_append_chararray.htm
Java.lang.StringBuilder.append() Method
package com.tutorialspoint; import java.lang.*; public class StringBuilderDemo { public static void main(String[] args) { StringBuilder str = new StringBuilder("compile "); System.out.println("string = " + str); // char array char[] cArr = new char[]{'o','n','l','i','n','e'}; /* appends the string representation of char array argument to this StringBuilder */ str.append(cArr); // print the StringBuilder after appending System.out.println("After append = " + str); } }