How to represent empty char in Java Character class

I want to represent an empty character in Java as "" in String...

Like that char ch = an empty character;

Actually I want to replace a character without leaving space.

I think it might be sufficient to understand what this means: no character not even space.


Solution 1:

You may assign '\u0000' (or 0). For this purpose, use Character.MIN_VALUE.

Character ch = Character.MIN_VALUE;

Solution 2:

char means exactly one character. You can't assign zero characters to this type.

That means that there is no char value for which String.replace(char, char) would return a string with a diffrent length.

Solution 3:

As Character is a class deriving from Object, you can assign null as "instance":

Character myChar = null;

Problem solved ;)

Solution 4:

An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.

You say you want to "replace a character without leaving a space".

If you are dealing with a char[], then you would create a new char[] with that element removed.

If you are dealing with a String, then you would create a new String (String is immutable) with the character removed.

Here are some samples of how you could remove a char:

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

    String s = "abcdefg";
    int index = s.indexOf('d');

    // delete a char from a char[]
    char[] array = s.toCharArray();
    char[] tmp = new char[array.length-1];
    System.arraycopy(array, 0, tmp, 0, index);
    System.arraycopy(array, index+1, tmp, index, tmp.length-index);
    System.err.println(new String(tmp));

    // delete a char from a String using replace
    String s1 = s.replace("d", "");
    System.err.println(s1);

    // delete a char from a String using StringBuilder
    StringBuilder sb = new StringBuilder(s);
    sb.deleteCharAt(index);
    s1 = sb.toString();
    System.err.println(s1);

}