Empty Character Literal in Java

  1. Use Empty Single Quotes to Represent a Null or Empty Character Literal in Java
  2. Use Character.MIN_VALUE or Unicode to Represent Empty Character Literal in Java

In Java, the char keyword represents the primitive data type used to declare char type variables and methods. This tutorial will introduce how we can declare a null or empty character literal and what error we face in achieving it.

Use Empty Single Quotes to Represent a Null or Empty Character Literal in Java

The simple solution that comes up in our mind when we ran into such situations where we have to declare an empty char is to assign '' as a char. This approach leads to an error given below.

public class CharacterCheck  {
    public static void main(String args[]){
       char a = '';
       System.out.println("char a is : "+a);
    }
}

Output:

java: empty character literal

Use Character.MIN_VALUE or Unicode to Represent Empty Character Literal in Java

To go around the problem of the empty character literal error is to assign the char type variable with the values given below.

We assign char1 with \u0000, which is the lowest range of the Unicode system used by Java. Similarly char2 is assigned Character.MIN_VALUE also the smallest value of type char, '\u0000'. Finally, char3 is assigned \0 special character, which represents null.

The replace() method looks in the given string for a particular character and returns a new string where the specified character is replaced. For replacedText, the replace() method replaces 'a' char from the text with an empty char. The new string is shown in the output.

public class CharacterCheck  {
    public static void main(String args[]){
        char char1 = '\u0000';
        char char2 = Character.MIN_VALUE;
        char char3 = '\0';
        String text = "How to replace any char in this string with null/empty character?";
        String replacedText = text.replace('a',char1);
        String replacedText1 = text.replace('t',char2);
        String replacedText3 = text.replace('s',char3);

        System.out.println("Replaced with null char : "+replacedText);
        System.out.println("Replaced with null char : "+replacedText1);
        System.out.println("Replaced with null char : "+replacedText3);
    }
}

Output:

Replaced with null char : How to replce ny chr in this string with null/empty chrcter?
Replaced with null char : How o replace any char in his sring wih null/empy characer?
Replaced with null char : How to replace any char in thi tring with null/empty character?
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java Char

  • Char to Uppercase/Lowercase in Java
  • Add Char to String in Java